我正在尝试实现一个简单的客户端服务器程序,该程序将持续交换消息,直到客户端决定停止。我找到了很多关于这个主题的教程,但是我正在努力正确地实现循环。服务器处理第一个请求但不处理其他请求。
这可能是一些愚蠢的错误,所以请原谅我提出这样一个基本问题 - 我是套接字的新手。我很乐意提供任何帮助。我提供了所有代码(基于我发现的一些示例):
客户端:
public class Client {
public static void main(String argv[]) throws Exception {
talkWithServer();
}
private static void talkWithServer() throws UnknownHostException, IOException {
String sentence;
String serverResponse;
BufferedReader brClient = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9000);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader brServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true) {
sentence = brClient.readLine();
out.writeBytes(sentence + '\n');
serverResponse = brServer.readLine();
System.out.println(serverResponse);
if (serverResponse.contains("<BYE>")) {
break;
}
}
clientSocket.close();
}
}
服务器:
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9000);
Protocol protocol = new Protocol();
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
}
}
}
协议:
public class Protocol {
public String processInput(String theInput) {
String theOutput = "> " + theInput;
return theOutput;
}
}
为简化调试,我简化了示例。感谢您的任何提示!
答案 0 :(得分:2)
我的猜测是“Socket connectionSocket = welcomeSocket.accept();” 如果我没记错的话,这将尝试每次接受新的客户端,并且由于你只连接一个,它将在第二次迭代中永远等待该行。 我建议你在while循环之前粘贴该行。
答案 1 :(得分:0)
尝试以下
Socket connectionSocket = welcomeSocket.accept();
while (true) {
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
outToClient.flush();
}