james_dean
james_dean

Reputation: 1517

Client Server Application Not Working

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.

Upvotes: 0

Views: 44

Answers (1)

robermann
robermann

Reputation: 1722

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.

Upvotes: 2

Related Questions