0
我正在創建一個TCP客戶端 - 服務器連接,其中客戶端向服務器發送兩個數字,並且服務器返回它們的總和。我的TCPServer.java類似乎有問題。它保持返回「套接字關閉」而不返回任何總和。經過多次測試後,程序停止在我分割字符串的部分(要添加的兩個數字用逗號分隔)。我的TCP客戶端 - 服務器連接有什麼問題?
這是怎麼回事?並且它與我關閉緩衝區的位置有什麼關係?
public class TCP_ServerThread extends Thread{
Socket connectionSocket2;
public TCP_ServerThread(Socket connectionSocket)
{
this.connectionSocket2=connectionSocket;
}
public void run(){
try{
Socket connectionSocket=this. connectionSocket2;
BufferedReader inFromClient =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
String clientsentence = inFromClient.readLine();
String[]arr=clientsentence.split(",");
System.out.println(arr[0]);
System.out.println(arr[1]);
int sum=Integer.parseInt(arr[0])+Integer.parseInt(arr[1]);
outToClient.writeBytes(Integer.toString(sum));
outToClient.close();
}
catch(Exception n)
{
System.out.println("cannot connect");
}
}
這裏是TCPClient.java類
public class TCP_ClientThread extends Thread {
public static int summ=0,portNum;
public static String ip;
public TCP_ClientThread(String ip,int port)
{
this.ip=ip;
this.portNum=port;
}
@Override
public void run() {
try{
TCPClient.gate.await();
int clientNum=summ++;
int firstNumber,secondNumber;
try{
//
Random num=new Random();
firstNumber=num.nextInt();
System.err.println("first no of client "+clientNum+"is"+firstNumber);
secondNumber=num.nextInt();
System.err.println("second no of client "+clientNum+"is"+secondNumber);
//---------------*open socket-----------------------------------
String ipp=this.ip;
int portt=this.portNum;
Socket ClientSocket = new Socket (ipp,portt);
//------------* input and output buffer---------------------------------------
DataOutputStream OutToServer = new DataOutputStream (ClientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader (new InputStreamReader(ClientSocket.getInputStream()));
System.out.println("connected");
//------------------* data inside buffer-----------------------------------
String data1=Integer.toString(firstNumber);
String data2=Integer.toString(secondNumber);
String data=(data1.concat(",")).concat(data2);
//-----------------------*Send to server-------------------------------
OutToServer.writeBytes(data);
OutToServer.close();
System.err.println("send packet of "+clientNum);
//---------------------------------------------------------------------------------
//-----------------------**Receive--------------------------------------
String sum = inFromServer.readLine();
// inFromServer.close();
System.out.println("sum of "+clientNum+"= "+sum);
ClientSocket.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
catch(Exception b)
{
System.out.println("gate");
}