gpt4 book ai didi

java - 我的 Java 服务器端未读取来自 Java 客户端的更多传入消息

转载 作者:行者123 更新时间:2023-12-01 22:22:55 25 4
gpt4 key购买 nike

我用Java创建简单的服务器-客户端程序我的服务器是

public class Server {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static BufferedReader bufferedReader;
private static String inputLine;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try
{
serverSocket = new ServerSocket(5000);
clientSocket = serverSocket.accept();
// Create a reader
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Get the client message
while((inputLine = bufferedReader.readLine()) != null)
System.out.println(inputLine); //Print
}catch(IOException e){
System.out.println(e);
}
}

}客户端是:

public class Client {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String hostName = "localhost";
try (
Socket echoSocket = new Socket(hostName, 5000);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in= new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
System.exit(1);
}

}

}

为什么我的服务器不再读取?当我调试程序时,我的程序在服务器中时会脱离循环..我不知道为什么

最佳答案

你的服务器看起来没问题。您的服务器无法读取多次的原因是客户端上的这一行:

System.out.println("echo: " + in.readLine());

客户端期望服务器给出答复,但您的服务器不会发回任何内容。因此删除上面的行或让服务器发送响应。

关于java - 我的 Java 服务器端未读取来自 Java 客户端的更多传入消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368560/

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