0

I have a server/client chat room. When the client connects to the server, and sends a message, the client program prints out the message that it sent, but on another client program that is connected to the server, it does not print out until the user presses the 'enter' key.

On the client side:

try {
    //Strings to hold messages in and out:
        String userinput, serverinput;
    
        //Getting input from the user:
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        
        //Messages from the server will be printed to the console, messages from console will be sent to the socket:
        while(true) {
            userinput = input.readLine();
            serverout.println(username + "> " + userinput);
            
            serverinput = clientin.readLine();
            System.out.println(serverinput);
        }
    }

On the server side:

public void run() {
            PrintWriter output = null;
            BufferedReader input = null;
            String message;
            SchoolRoomServer server = new SchoolRoomServer();;
            try {
                //i/o for clients:
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException ioe) {
                System.err.println(ioe);
                System.exit(1);
            }
            
            try {
                while((message = input.readLine()) != null) {
                    server.showAll(message, output);
                }
            } catch (IOException ioe) {
                System.err.println(ioe);
                System.err.println("Damn errors.");
                System.exit(1);
            }
        }

By the way- the server.showAll(message, output); method is this:

public void showAll(String msg, PrintWriter printwriter) {
    for(int i = 0; i < listWriters.size(); i++) {
        if(listWriters.get(i) != printwriter) {
            listWriters.get(i).println(msg);
        }
    }
}

listWriters is an Arraylist of PrintWriters, which gets a PrintWriter associated with a client each time a new thread is made for that client.

So, do any ideas on how to immediately print out messages?

Bl H
  • 133
  • 4
  • 12
  • By the way, I am quite new to Java- where would I use the flush() method to print it out straight away? – Bl H Jun 18 '12 at 07:27

2 Answers2

0

You are having the same problem as here. System.in doesn't return anything until the user pressed enter. Then you get the whole line to read.

Community
  • 1
  • 1
Marc
  • 3,550
  • 22
  • 28
0

Read on Socket & ServerSocket

Basically you need to establish a client socket which connects to a server socket then you need to pass the i/o streams between the two to print messages from the client to the server & vice-versa.

Rahul Thakur
  • 882
  • 16
  • 31