gpt4 book ai didi

java - 具有循环消息传递的简单客户端服务器

转载 作者:行者123 更新时间:2023-12-02 04:48:44 25 4
gpt4 key购买 nike

我正在尝试实现一个简单的客户端服务器程序,它将不断交换消息,直到客户端决定停止。我发现了很多关于这个主题的教程,但是我在正确实现循环方面遇到了困难。服务器处理第一个请求,但不处理其他请求。

这可能是一些愚蠢的错误,所以请原谅我问这样的基本问题 - 我是套接字新手。我很乐意提供任何帮助。我提供了所有代码(基于我找到的一些示例):

客户:

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');
}
}
}

协议(protocol):

public class Protocol {

public String processInput(String theInput) {
String theOutput = "> " + theInput;


return theOutput;
}
}

为了更容易调试,我简化了示例。感谢您的任何提示!

最佳答案

我的猜测是“Socket connectionSocket =welcomeSocket.accept();”行如果我没记错的话,这将尝试每次接受新的客户端,并且由于您只连接一个,它将在第二次迭代中永远等待该线路。我建议您将该行粘贴到 while 循环之前。

关于java - 具有循环消息传递的简单客户端服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29445391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com