I’m trying to send data from client socket to the server but, when data is sent, server is still waiting for data, after this the client socket then waiting for a data from server. There are two sockets waiting each other. Could someone explain what is wrong:
Client:
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++;
}
}
}
Server:
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();
}
}
}
Your server uses
readLine, which will wait for a complete line. Your client usesprintwhich doesn’t append an end-of-line marker. So the server is waiting for that end-of-line.Use
printlnin the client (and do the same for the return exchange), and things should get “unstuck”.