简体   繁体   中英

Trying to make send a message when the enter key is pressed

I am trying to send a message to the server. My problem is that the client keeps waiting for input and never sends it to the server until the last message that tells it to terminate (which is "bye"). After client terminates, the server will receive the message. But I want the server to receive the message everytime the client hit's the enter key.

I am not sure, but I think that the problem is with the Bufferedwriter in the client, because if I connect to the server using the browser, the server receives all the browser information. An example is shown below:

Connect to this server name: localhost and port: 121
Connection from client: Socket[addr=/0:0:0:0:0:0:0:1,port=61942,localport=121]
From client > GET / HTTP/1.1
From client > Host: localhost:121
From client > Connection: keep-alive
From client > Cache-Control: max-age=0
From client > Upgrade-Insecure-Requests: 1
From client > User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36
...

Relevant server code:

try {
    sers = new ServerSocket(port);
    client = sers.accept();
    
    reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
    
    boolean clientIsOnline = true;
    
    while (clientIsOnline) {
        print("Connection from client: " + client);
        
        while((msg = reader.readLine()) != null) {
            print("From client > " + msg);
            if(msg.toLowerCase().equals("bye"))
                print("Client left, server closed");
                clientIsOnline=false;
        }
        ss.close();
        reader.close();
        writer.close();
    }
    
} catch(Exception e) {
    print("Error starting  server: ");
    e.printStackTrace();
}

Relevant client code:

public Client(String adr, int port) {
    this.adr=adr;
    this.port=port;
    try {
        c=new Socket(adr, port);
        r = new BufferedReader(new InputStreamReader(c.getInputStream()));
        w = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));

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

Client method for sending the message

private void msgToServer(String msg) {
    try {
        w.write(msg);
        w.flush();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if(msg.toLowerCase().equals("bye")) {
        print("I am out, bye");
        try {
            c.close();
            r.close();
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client main method:

public static void main(String[] args) {

        int port=121;
        String msg =null;

        Scanner sc = new Scanner(System.in);
        Client c = new Client("localhost", port);

        System.out.println("Write something to server");
        while(true) {
            c.msgToServer(sc.next());
        }
    }

I also tried using the PrintWriter instead of BufferedWriter, and also tried adding the true keyword as parameter, like

new PrintWriter(new OutputStreamWriter(c.getOutputStream()), true);

Just to give an example of what it looks like using my client.

I type hello hit enter (I expect it to send this, but it doesn't). Then I type my name is john hit enter again. Finally I type bye I excpect:

From client > hello
From client > my name is john 
From client > bye

What I get: From client > hellomynameisjohnbye

I believe the newline is being consumed when the client reads the input, so it needs to be added when sent to the server. In the client method:

private void msgToServer(String msg) {
    try {
        // re-introduce newline:
        w.println(msg);

    [SNIP]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM