简体   繁体   English

从客户端向服务器发送消息

[英]Send messages from client to server

I'm having problems sending messages from client to server and to server to other clients.我在将消息从客户端发送到服务器以及从服务器发送到其他客户端时遇到问题。 Please can you give me a hand by telling me something.请告诉我一些事情,请你帮我一把。 The problem is if I do an input (line 46) I can get an answer from the server (line 51) then continue this loop.问题是如果我进行输入(第 46 行),我可以从服务器(第 51 行)得到答案,然后继续这个循环。 But for example, if the server must notify a user that it's his turn, I wouldn't get the message until I try typing something.但是例如,如果服务器必须通知用户轮到他了,那么在我尝试输入内容之前我不会收到消息。

while ((userInput = stdIn.readLine()) != null) {
    /* line 46 */ out.println(userInput);
    if (userInput.equals("quit")) {
        break;
    }

    /* line 51 */ lines = in.readLine();
    System.out.println(lines);

    System.out.println("input next command:");
}

You have to make (at least i dont know how else to do it) a separate thread where you get user input, then use message passing (just search "message passing java") for comunication.您必须制作(至少我不知道该怎么做)一个单独的线程,您可以在其中获取用户输入,然后使用消息传递(只需搜索“消息传递 java”)进行通信。 Server messages will not get blocked by input and you can tryReceive (or some name around that lines) on channel.服务器消息不会被输入阻止,您可以在通道上tryReceive (或该行周围的某些名称)。 In main thread query for message from server, then from input channel, sleep a little and repeat.在主线程中从服务器查询消息,然后从输入通道,休眠一点并重复。 When user presses enter, channel gets filled with his message, main thread takes it when passing by.当用户按下回车键时,通道被他的消息填满,主线程在经过时接受它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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