Question

Here is my problem, have a server and a client class which communicate via 2 threads (MsgWriter and MsgReader)

To read the input and write it in a stream i use a scanner. It works but the Scanner need an input twice to continue.

For example: I write a Message Your Message: a text.

So i want to send the message right after i hit "enter" but i have to press enter another time to send the text.

I'm sorry, i'm very bad in explaining. however here is the Code of the MsgWriter Thread

public class MsgWriter extends Thread {

    private Socket s;
    private Buffer buffer = new Buffer();
    public MsgWriter(Socket s) {
        this.s = s;
    }

    public void run() {


        String message = "";
        BufferedReader br = null;
        boolean end = false;
        while(!end){
            try{
                synchronized (buffer) {
                    while (!buffer.isEmpty()) {
                        buffer.wait();
                    }
                    //buffer.put(s);
                OutputStream out = s.getOutputStream();
                PrintStream writer = new PrintStream(out);
                Scanner input = new Scanner(System.in);
                input.useDelimiter("\n");
            if (input.nextLine().equals("")){
                    System.out.println("Your message: ");

                    message = input.next();
                    br = new BufferedReader(new StringReader(message));

                     if (input.hasNext("x")) {
                        br = new BufferedReader(new StringReader("Good Bye"));
                        end = true;
                    }
                    message = br.readLine();
                    writer.println(message);
                    System.out.println("-------------------------------");
                }

            buffer.notifyAll();
                }

            }catch(Exception ex){
                System.out.println(ex.getMessage());
            }

        }

    }
}

And the Output

ServerIP: localhost/127.0.0.1 Port number: 56763 ++ Connected to Server

Your message: hi server


Received: hi client

Let me know if you need the Code of the MsgReader Thread as-well.

Was it helpful?

Solution

You have this line if (input.nextLine().equals("")) which looks for an empty string input and this is the reason your code waits for the second 'Enter' press. Any specific reason why you require this in the code?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top