gpt4 book ai didi

java - TCP Server 只接收一条消息

转载 作者:可可西里 更新时间:2023-11-01 02:39:11 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 TCP 服务器和客户端。我希望客户端能够通过只打开一次套接字来发送多条消息。我看过类似的问题here , here , 和 here但它们并没有多大用处。

我的代码如下:

SampleServerTCP.java

public class SampleServerTCP {
private static final int DEFAULT_PORT_NUMBER = 39277;

public static void main(String[] args) throws IOException {
ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}
}
}

TCPClientTest.java

public class TCPClientTest {

public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
Socket clientSocket = new Socket("localhost", 39277);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

int c = 0;
while(c<10){
outToServer.writeBytes(c + "\n");
outToServer.flush();
c++;
Thread.sleep(500);
}
clientSocket.close();
}
}

我得到的唯一输出是:

Listening on port: 39277
Recieved: 0

我哪里错了?

最佳答案

你的问题出在这里:

ServerSocket defaultSocket = new ServerSocket(DEFAULT_PORT_NUMBER);

System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
while (true){
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = fromClient.readLine();
System.out.println("Recieved: " + msg);
}

您正在打开套接字,只读取一行,然后等待下一个套接字。

相反,您应该在 while 循环之外执行 Socket connectionSocket = defaultSocket.accept();,并在循环中从该套接字读取数据,如下所示:

System.out.println("Listening on port: " + DEFAULT_PORT_NUMBER);
Socket connectionSocket = defaultSocket.accept();
BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
String msg = "";
while ((msg = fromClient.readLine()) != null){
System.out.println("Recieved: " + msg);
}

关于java - TCP Server 只接收一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32090470/

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