gpt4 book ai didi

java - 如何在没有客户端提示的情况下接收从服务器到客户端的消息

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:17 26 4
gpt4 key购买 nike

所以我正在制作一个基本的聊天应用程序。这是来自客户端的代码片段。这里我向服务器发送信息,然后得到回复。

但是,有时服务器会向客户端发送消息,而不需要客户端先向服务器发送信息。我该如何实现这个?

while (true){    
String sentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();

// send to server
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("\n");

// create read stream and receive from server
BufferedReader FromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println(FromServer.readLine());


}

例如,服务器可能会以随机间隔向我发送随机信息。但只有当我先向服务器发送一些东西时我才能收到它们。但如果我实现类似的东西(如下所示),我将不再能够向服务器发送信息,只能充当接收者。但我希望能够在必要时发送信息和接收信息,而不必先发送某些内容。

while (true){    

// receive from server only
BufferedReader FromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println(FromServer.readLine());


}

我在回复第一条评论时更改了什么。我遵循了你的代码,所以这就是我所做的。但是,我似乎仍然无法自发地接收消息,即我仍然需要按 Enter 或键入输入来接收随机发送的任何服务器信息:

BufferedReader FromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (true) {
// Check if there's anything to receive
while (FromServer.ready()) {
// receive from server
System.out.println(FromServer.readLine());
}

String sentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();

// write to server
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence + '\n');

// Send data to the server here if required.
}

最佳答案

将其更改为这样的内容:-

BufferedReader FromServer = 
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

while (true) {
// Check if there's anything to receive
while (FromServer.ready()) {
// receive from server
System.out.println(FromServer.readLine());
}
if (inFromUser.ready()) {
int ch = inFromUser.read();

// write to server
outToServer.writeChar(ch);
}


}

现在客户端将读取任何要读取的内容,并且可以在需要时发送数据。

关于java - 如何在没有客户端提示的情况下接收从服务器到客户端的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43660776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com