gpt4 book ai didi

java - tcp客户端和服务器不互相接收数据

转载 作者:行者123 更新时间:2023-11-30 04:49:31 26 4
gpt4 key购买 nike

我正在尝试从客户端套接字向服务器发送数据,但是,当发送数据时,服务器仍在等待数据,在此之后客户端套接字然后等待来自服务器的数据。有两个套接字互相等待。有人可以解释一下出了什么问题吗:

客户:

package ssd8ex3_tcp_client;

import java.io.*;
import java.net.*;

public class Ssd8Ex3_TCP_Client {

private static final int SERVICE_PORT = 2000;

public static void main(String[] args) {

String hostname = "localhost";

int counter = 0;
while (counter < 1000) {
try {
Socket socket = new Socket(hostname, SERVICE_PORT);
socket.setSoTimeout(50000);
PrintStream pstream = new PrintStream( socket.getOutputStream() );
pstream.print(counter);
pstream.flush();

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = reader.readLine();
System.out.println("Results :" + s);
socket.close();

} catch (IOException e) {
e.printStackTrace();
}

counter++;
}

}
}

服务器:

package ssd8ex3_tcp_server;

import java.io.*;
import java.net.*;


public class Ssd8Ex3_TCP_Server {

public static final int SERVICE_PORT = 2000;

public static void main(String[] args) {
try {
ServerSocket server_socket = new ServerSocket(SERVICE_PORT);

System.out.println("Server started");

for(;;){
Socket nextClient = server_socket.accept();
System.out.println("Received request from " + nextClient.getInetAddress() + ":" + nextClient.getPort());

BufferedReader reader = new BufferedReader(new InputStreamReader(nextClient.getInputStream()));
String s = reader.readLine();
OutputStreamWriter out = new OutputStreamWriter(nextClient.getOutputStream());
PrintWriter pout = new PrintWriter(out);

pout.print(s);

out.flush();

nextClient.close();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

您的服务器使用readLine,它将等待完整的行。您的客户端使用 print ,它不会附加行尾标记。所以服务器正在等待行尾。

在客户端中使用println(并对返回交换执行相同的操作),事情应该会“解开”。

关于java - tcp客户端和服务器不互相接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10154571/

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