Reputation: 180
I am trying to make a simple client and server for sending and receiving text. Client waits for command line input and then sends it to server which displays it on System.out
. But the server gets stuck at reading from socket although the client allows me to type next line to send.
Client:
public class Main implements Runnable{
String [] args;
Socket socket;
PrintWriter printer;
public Main(String [] args){
this.args = args;
}
@Override
public void run() {
try {
socket = new Socket(args[0], Integer.parseInt(args[1]));
printer = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e){
System.out.println("Unknown host.");
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
}
while(true){
String textToSend = System.console().readLine();
printer.print(textToSend);
}
}
}
The line printer.print(textToSend);
does not work.
Server:
public class Main implements Runnable{
String [] args;
public Main(String [] args){
this.args = args;
}
@Override
public void run() {
if (args == null){
System.out.println("Argument for port missing");
System.exit(2);
}
try {
ServerSocket listener = new ServerSocket(Integer.parseInt(args[0]));
while (true){
Socket client = listener.accept();
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
try{
while(true){
String text = in.readLine();
System.out.println(text);
if (in.read() == -1){
return;
}
}
}catch (IOException e){
System.out.println("Client lost");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Any help would have been welcome.
Upvotes: 0
Views: 72
Reputation: 44854
When you are doing
if (in.read() == -1){
return;
}
you are throwing away one char
Also, when you are writing
printer.print(textToSend);
the textToSend does not have a CR
so the receiving readLine
will block.
Try adding a CR
to the end of textToSend
or use the println
method
Upvotes: 2
Reputation: 4872
I found the error: You have to add the newline character and call flush:
printer.print(textToSend + "\n");
printer.flush();
This works for me.
Flush forces to send all the data and empty all the buffers so data is send. The newline is needed, so that the receiving end knows the line is complete.
Your check to see if no data was send should be line == null
, not read() == -1
.
This is my whole demo code:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String textToSend = null;
try {
textToSend = reader.readLine();
System.out.println("read text: " + textToSend);
} catch (IOException e) {
e.printStackTrace();
}
printer.print(textToSend + "\n");
printer.flush();
System.out.println("text send");
}
Error check on the server side:
String text = in.readLine();
if (text == null){
return;
}
System.out.println(text);
Upvotes: 0