1

So I am implementing a simple Java Socket Chat program, but the problem I encountered is that in the Code below. Currently my client code will first read from socket then output to the screen , then read from console then output to socket input. But this way Im unable to print messages from socket when it is reading from console untill the user hits enter What would be the best way to solve this problem, is it Multithreading (if so can i get an example?), or is there any other conventional way of dealing with this.

        while(true){
            //read from socket, -> output to screen
            String line = sockin.readLine();
            System.out.println(line);

            //read console, -> write to socket
            String consolein = consoleReader.readLine();
            sockout.println(consolein);
        }

1 Answer 1

4

Yes, you should be using Multithreading. You need to spawn two threads, one for reading input from user and another for reading output from server/another client. But, one concern while using Multithreading for console based chat application is: separation of the output from server and input from user.

Sample Multithreaded Client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ThreadedClient {

    public static void main(String[] args) {
        if (args.length != 2) {
            System.err.println(
                    "Usage: java ThreadedClient <host name> <port number>");
            System.exit(1);
        }

        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);

        try {
            Socket serverSocket = new Socket(hostName, portNumber);
            ClientServerOutputReader csor = new ClientServerOutputReader(serverSocket);
            csor.start();
            ClientUserInputReader cuir = new ClientUserInputReader(serverSocket);
            cuir.start();
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    hostName);
            System.exit(1);
        } 
    }

}

class ClientServerOutputReader extends Thread {
    Socket serverSocket;
    public ClientServerOutputReader(Socket serverSocket){
        this.serverSocket = serverSocket;
    }

    public void run() {
        try {
            BufferedReader in = new BufferedReader(
            new InputStreamReader(serverSocket.getInputStream()));

            String outputFromServer="";
            while((outputFromServer=in.readLine())!= null){
                //This part is printing the output to console
                //Instead it should be appending the output to some file
                //or some swing element. Because this output may overlap
                //the user input from console
                System.out.println(outputFromServer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class ClientUserInputReader extends Thread {
    Socket serverSocket;
    public ClientUserInputReader(Socket serverSocket){
        this.serverSocket = serverSocket;
    }
    public void run(){
        BufferedReader stdIn = new BufferedReader(
                 new InputStreamReader(System.in));
        PrintWriter out;
        try {
            out = new PrintWriter(serverSocket.getOutputStream(), true);
            String userInput;

            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To run: java ThreadedClient localhost 1982

Sample echo server

import java.net.*;
import java.io.*;

public class EchoServer {
    public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
        }

        int portNumber = Integer.parseInt(args[0]);

        try (
            ServerSocket serverSocket =
                new ServerSocket(Integer.parseInt(args[0]));
            Socket clientSocket = serverSocket.accept();     
            PrintWriter out =
                new PrintWriter(clientSocket.getOutputStream(), true);                   
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
        ) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                out.println("From Server:"+inputLine);
                Thread.sleep(2000);
                out.println("Server status on");
            }
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        } catch (InterruptedException ie) {
             ie.printStackTrace();
        }
    }
}

In the server program above, manual sleep and custom message is added to simulate the output from server when there is an user input happening in client.

To run: java EchoServer 1982

1
  • thank you although I was doing something similar subclassing Thread, but now Im outputting using Swing which solves the problems. thanks
    – natgeo201
    Sep 15, 2015 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.