Reputation: 5743
I use this Thread at server side in order to receive Strings from client:
int clientNumber = 0;
ServerSocket listener = new ServerSocket(6543);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
...
private static class Capitalizer extends Thread {
private Socket socket;
private int clientNumber;
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String input = in.readLine();
System.out.println("Am Server: " + input);
out.println(input.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
}
And the client looks like this:
try {
Socket client = new Socket("localhost", 6543);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter something : ");
String input = br.readLine();
out.write(input.getBytes());
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
It is not clear for me that at server side no string is received. I enter a string in Eclipse console and at client this string is sent to server but at server side nothing happens. Does anyone have a hint what I'm doing wrong?
Upvotes: 0
Views: 87
Reputation: 182855
Your server expects to receive lines, so your client must send lines. But your client does not send lines. Why?
From the docs:
Return Value
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
Thus the return value of readline
is not a line since, as that same page says:
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
To avoid this mistake in the future, before you use TCP, specify in writing precisely what information will be sent and received. If you're using TCP to exchange messages, defined precisely what a message is -- at the byte level.
For this application, you should have precisely specified that the messages will consist of a sequence of characters not including any line terminator characters whose end is marked with a line ending. That would have made it clear that the client was buggy, since it's obviously not sending messages as specified by the protocol.
Upvotes: 2