我正在创建一个TCP客户端 - 服务器连接,其中客户端向服务器发送两个数字,服务器返回它们的总和。我的TCPServer.java类似乎有问题。它不停地返回“Socket closed”而不返回任何总和。多次测试后,程序停止在我拆分字符串的部分(用逗号分隔的两个数字)。
出了什么问题?它与我关闭缓冲区的位置有什么关系吗?
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");
}
答案 0 :(得分:0)
'Socket closed'表示你关闭套接字然后继续使用它。
关闭套接字的输入或输出流也会关闭套接字。