所以我正在制作一个基本的聊天应用程序。这是来自客户端的代码片段。在这里,我将信息发送到服务器,然后得到答复。
但是,有时服务器会向客户端发送消息,而不需要客户端首先向服务器发送信息。我该如何实现呢?
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());
}
我在回复第一条评论时所做的更改。我按照你的代码,这就是我做的。但是,我似乎仍然无法自发地接收消息,即我仍然需要输入或输入输入以接收随机发送的任何服务器信息:
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.
}
答案 0 :(得分:0)
将其更改为: -
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);
}
}
现在,客户端将读取任何要读取的内容,并且可以在需要时发送数据。