【发布时间】:2023-03-16 21:05:01
【问题描述】:
我正在尝试创建一个简单的 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
我哪里错了?
【问题讨论】:
-
您的服务器只读取一条消息。你为什么感到惊讶?