0

I am trying to write a simple client/server Echo application, my client seems to be sending the input, but the server doesn't seem to pick it up and send it back.

Here's the server:

import java.io.*; import java.net.*; public class Server { public static void main(String args[]) throws Exception { int port = 2000; ServerSocket serverSocket; Socket client; BufferedReader is = null; BufferedWriter os = null; serverSocket = new ServerSocket(port); System.err.println("Server established on port " + port); client = serverSocket.accept(); System.err.println("Client connected"); is = new BufferedReader( new InputStreamReader(client.getInputStream())); os = new BufferedWriter( new OutputStreamWriter(client.getOutputStream())); System.err.println("Server established on port " + port); String message = ""; while((message = is.readLine()) != null) { System.err.println("Messaged received " + message); os.write(message); } is.close(); os.close(); serverSocket.close(); } } 

Then, the client looks like this:

import java.io.*; import java.net.Socket; public class Client { public static void main(String args[]) throws Exception { String host = "localhost"; int port = 2000; Socket socket; socket = new Socket(host, port); BufferedReader is = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedWriter os = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); System.err.println("Connected to " + host + " on port " + port); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = ""; while((input = br.readLine()) != null) { System.out.println("Sending " + input); os.write(input); System.out.println("Receiving " + is.read()); } is.close(); os.close(); socket.close(); } } 

What am I missing, I am sure I overlooking something simple.

1
  • Flush the streams after you write to them maybe? Also you should consider using ARM, or a try catch finally to manage those resources... Commented Mar 6, 2014 at 17:06

1 Answer 1

2

In the client, try writing the message with a final newline char:

os.write(input+"\n"); 

(or call also newLine())

That because the server is reading line-by-line.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.