Reputation: 135
For some reason I am not able to read lines from the client on the server. The client is able to send lines without a problem but the server wont move past the first time clientIn.readLine() is called. I assume it is blocking but I don't know how to deal with it.
This also occurred when I sent lines without the server side loop.
Client.java
public void run()
{
try {
socket = new Socket(ip, port);
System.out.println("Client connected on port: " + socket.getRemoteSocketAddress());
//wrap streams for ease
BufferedReader serverIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter serverOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.println("starting messages");
//send messages
serverOut.println("hello from: " + socket.getLocalSocketAddress());
serverOut.println("msg1: " + this.hashCode());
serverOut.println("msg2: final test");
//close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Server.java:
public void run()
{
System.out.println("Server Running on port: " + serverSocket.getLocalPort());
while(true)
{
try {
//listen for connections
Socket client = serverSocket.accept();
//record sockets
connections.put(client.getRemoteSocketAddress(), client);
//wrap streams for ease
BufferedReader clientIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter clientOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));
//send messages
String line = null;
while((line = clientIn.readLine()) != null)
{
System.out.println(line);
}
//ends the connection
client.close();
System.out.println("Client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 3
Views: 260
Reputation: 311052
socket.close();
You are closing the socket where you should be closing the PrintWriter
:
serverOut.close();
You're losing buffered data in the PrintWriter
when you close the socket out from under it.
Upvotes: 5
Reputation: 692231
You need to flush()
your serverOut
writer, otherwise your messages stay in the buffer of the BufferedWriter and are never sent to the server.
Upvotes: 3