尝试在按下回车键时发送一条消息。

huangapple go评论61阅读模式
英文:

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

问题

我试图向服务器发送一条消息。我的问题是,客户端一直在等待输入,直到最后一条告诉它终止的消息(即"bye")。客户端终止后,服务器将接收到消息。但我希望每次客户端按下回车键时,服务器都能接收到消息。

我不确定,但我认为问题出在客户端的BufferedWriter上,因为如果我使用浏览器连接到服务器,服务器会接收到浏览器的所有信息。下面是一个示例:

连接到此服务器名称:localhost,端口:121
来自客户端的连接:Socket[addr=/0:0:0:0:0:0:0:1,port=61942,localport=121]
来自客户端 > GET / HTTP/1.1
来自客户端 > Host: localhost:121
来自客户端 > Connection: keep-alive
来自客户端 > Cache-Control: max-age=0
来自客户端 > Upgrade-Insecure-Requests: 1
来自客户端 > 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
...

相关的服务器代码:

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("连接来自客户端:" + client);
        
        while((msg = reader.readLine()) != null) {
            print("来自客户端 > " + msg);
            if(msg.toLowerCase().equals("bye"))
                print("客户端离开,服务器关闭");
                clientIsOnline=false;
        }
        ss.close();
        reader.close();
        writer.close();
    }
    
} catch(Exception e) {
    print("启动服务器时出错:");
    e.printStackTrace();
}

相关的客户端代码:

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();
    }
}

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("我走了,再见");
        try {
            c.close();
            r.close();
            w.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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("向服务器写点什么");
    while(true) {
        c.msgToServer(sc.next());
    }
}

我还尝试过使用PrintWriter代替BufferedWriter,并尝试添加true关键字作为参数,例如:

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

只是为了用我的客户端举个例子。

我输入 hello,按回车键(我期望它会发送这个消息,但实际上没有)。然后我输入 my name is john,再次按回车键。最后我输入 bye
我期望的输出是:

来自客户端 > hello
来自客户端 > my name is john 
来自客户端 > bye

但实际输出是:来自客户端 > hellomynameisjohnbye

英文:

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

答案1

得分: 1

我相信换行符在客户端读取输入时被消耗掉了,因此在发送到服务器时需要添加换行符。在客户端方法中:

private void msgToServer(String msg) {
    try {
        // 重新引入换行符:
        w.println(msg);

    [SNIP]
英文:

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]

huangapple
  • 本文由 发表于 2020年10月24日 18:59:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64512626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定