James Rogers
James Rogers

Reputation: 69

Chat Client/Server - How to instruct Client to Accept input from either Console or Server

How do you code a chat client so that it listens for input both from the server and from the console? This is my current client which successfully sends to and accepts input from the server. As you can see, it doesn't have any code that will enable it to successfully listen for and accept input from the console while also being open to input from the server. The server input would be messages from other chat clients. A message sent from any chat client is broadcast to all other clients. I am pretty new to Java and am completely stuck even though I have a feeling the answer will be depressingly obvious.

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 ChatClientMain
{
    public static void main(String[] args) throws UnknownHostException, IOException
    {
        //DNS of Chat Server
    final String HOST = "localhost";

    //Port number for chat server connection
    final int PORT = 6789;

    Socket serverSocket = new Socket(HOST, PORT);
    try
        {
        //Will need three streams for communication: console-client, client-server, server-client
        PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
        BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
        BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));

        //User must be logged in; any username is acceptable
        System.out.print("Enter username > ");
        toServer.println("LOGIN " + fromUser.readLine());

                String serverResponse = null;
        while((serverResponse = fromServer.readLine()) != null)
        {
                    System.out.println("Server: " + serverResponse);
            if(serverResponse.equals("LOGOUT"))
            {
                System.out.println("logged out.");
            break;
            }

            System.out.print("command> ");
            toServer.println(fromUser.readLine());
        }

                toServer.close();
            fromServer.close();
            fromUser.close();
            serverSocket.close();

            }
        catch (IOException e)
        {
        e.printStackTrace();
        }
      }
}

Upvotes: 0

Views: 295

Answers (1)

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

If your main thread is listening to the input from the server, you may start another thread that would keep listening for input from the console. You will have to ensure that you handle input properly. Some flag may be set to indicate if the input is from the server or from the console.

Upvotes: 1

Related Questions