So I made a Server and Client with sockets in Java. I’m trying to get the server to read/write from the socket, but it only reads once the client disconnects:
System.out.println("Server initialized");
clientSocket = server.accept();
System.out.println("Client connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
for(int loop = 0;loop<5;loop++){
out.write("Hello");
System.out.println(in.readLine());
} //end for
The problem is that once the client connects, it says “Client connected” but then it doesn’t run through the for loop. Once the client disconnects, however, the server executes the for loop and returns
null
null
null
null
null
What am I missing here? Here is my full server code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public ServerSocket server;
public Server(int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Cannot bind to port: "+ port);
System.exit(-1);
}
} //end constructor
public void WaitForClient() throws IOException{
Socket clientSocket = null;
try {
System.out.println("Server initialized");
clientSocket = server.accept();
System.out.println("Client connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
for(int loop = 0;loop<5;loop++){
out.write("Hello");
System.out.println(in.readLine());
} //end for
} //end try
catch (IOException e) {
System.out.println("Accept failed");
System.exit(-1);
} //end catch
clientSocket.close();
server.close();
} //end method
} //end class
(My main method is called from another class.)
You have to flush the stream on the server if you want to see the results immediately. The stream is auto-flushed on
close(), that’s why you seen the output then.