我正在尝试将数据从客户端套接字发送到服务器,但是,当发送数据时,服务器仍在等待数据,之后客户端套接字然后等待来自服务器的数据。有两个插座互相等待。有人可以解释什么是错的:
客户端:
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();
}
}
}
答案 0 :(得分:2)
您的服务器使用readLine
,它将等待一整行。您的客户使用的print
不会附加行尾标记。所以服务器正在等待该行尾。
在客户端使用println
(并为返回交换执行相同操作),事情应该“解开”。