2

I have created two classes one server and client, I send data via the socket input and output stream however cant send multiple messages?

Server:

public class SOK_1_SERVER {

    public static void main(String[] args) throws Exception
    {

        SOK_1_SERVER Sever = new SOK_1_SERVER();
        Sever.run();
    }

    private void run() throws Exception {
        ServerSocket SRVSOCK = new ServerSocket(444);
        //Waits both client and server to accept and we return 
        //a socket
        Socket SOCK = SRVSOCK.accept();
        //Once accepted 
        InputStreamReader isr = new InputStreamReader(SOCK.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String message = br.readLine();
        System.out.println("I read: " + message + "from Client");

        if(message != null)
        {
            //Sending message back to client 
            PrintStream ps = new PrintStream(SOCK.getOutputStream());
            ps.println("Message Received");
            ps.println("Send from Server");
        }
    }
}

Client

public class SOK_1_CLIENT {

    public static void main(String[]args) throws Exception
    {
        SOK_1_CLIENT client = new SOK_1_CLIENT();
        client.run();
    }

    private void run() throws Exception {
        Socket SOCK = new Socket("localhost",444);
        PrintStream ps = new PrintStream(SOCK.getOutputStream());
        ps.println("Hello to Server from client");

        InputStreamReader ir = new InputStreamReader(SOCK.getInputStream());
        BufferedReader br = new BufferedReader(ir);

        String message = br.readLine();

        System.out.println(message);

    }

}

It only outputs message received however I think its because I need to have a loop to keep checking for new messages however not sure as I have just started this looking into sockets.

1 Answer 1

1

In your client class, you need to iterate the bufferedReader .

instead of

 String message = br.readLine();

 System.out.println(message);

use this,

 String message ;
 while((message = br.readLine())!=null) {
     System.out.println(message);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the initializer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.