这是一个简单的java程序,它从客户端发送一个字符串到服务器,服务器将字符串的长度返回给客户端。
首先,我运行服务器,然后运行客户端,输入字符串但不按Enter,然后运行第二个客户端,输入字符串并按Enter。Enter然后,在按下第一个客户端之前,第二个客户端不会得到响应。我该如何解决这个问题?
TCP客户端
public class TCPClient {
public static void main(String[] args) throws Exception {
String sentence;
String sentenceLength;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("mycomputer", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
sentenceLength = inFromServer.readLine();
System.out.println(sentenceLength);
clientSocket.close();
}
}
TCP服务器
public class TCPServer {
public static void main(String[] args) throws Exception {
String clientSentence;
int clientSentenceLength;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
clientSentenceLength = clientSentence.length();
outToClient.writeBytes(clientSentenceLength + "" + '\n');
}
}
}
绝地无双
凤凰求蛊
相关分类