Reputation: 4460
I have following Server:
public final class Server implements Runnable {
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
Server() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
boolean running = true;
try {
serverSocket = new ServerSocket(5000);
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (running) {
String data = in.readLine();
System.out.println(data);
if (data.equals("quit")) {
running = false;
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
and following Client:
public class Client {
private Socket socket;
private PrintWriter out;
public Client() {
socket = null;
try {
socket = new Socket("127.0.0.1", 5000);
out = new PrintWriter(socket.getOutputStream());
} catch (final UnknownHostException e) {
System.err.println("Address unknown "
+ e.getMessage());
} catch (final IOException e) {
System.err.println("Error connecting to the Server "
+ e.getMessage());
}
}
public void sendMessage(String msg) {
out.println(msg);
}
}
I am able to establish an initial connection, but as soon as I execute the sendMessage()
Method, the server doesn't print out anything. Do you know why I cannot receive a message?
Upvotes: 1
Views: 360
Reputation: 11875
The server reads with in.readLine()
while the client prints with print()
(no new line). So the server is waiting for new line to appear which never happens.
Try writing with println()
in the client.
Also, you need to flush your writer: add out.flush()
. This is required to make the writer to actually send its payload.
Upvotes: 3