监听服务器发送尝试的正确方法

the proper way to listen for server sending attempt

例如确定服务器此时正在发送数据的正确方法是什么
伪代码

while(true){
  //Do something
  if(ServerIsSendingrightnow){
    //Get The Data
    //Calling some method to handling the server's data
  }
  //Do something else
}

InputStream 的 available() 方法 class 能完成任务吗?
代码:

 while(true){
   //Do something
   InputStream IStreamsock = Socket1.getInputStream();
   if(IStreamsock.available()){ //the server is sending data right now !
     //Get The Data
     //Calling some method to handling the server's data}
     //Do something else
}

在 C# 中,我们有 MemoryStream class 作为动态字节数组
是否有任何 java 等同于 MemoryStream
我可以在 java 中做这样的事情吗: 伪代码

 while(DataIsAvailableInSocketInputStreamBuffer){
   MemoryStreamEquivalent.WriteByte(IStreamsock.ReadByte())}

对不起,我是 java

的新人

不,available 的用法不是很有用,因为它并不像您期望的那样工作。只需使用 in.read()。它会等到服务器发送了一些东西。所以如果你在一个线程中使用它,它只会等到可以接收到一些东西。

编辑:它只接收一个字节,例如BufferedReader(读取字符串)是更好的解决方案,或者 ObjectInputReader(显然是对象)可能是更好的解决方案。当然需要 while(true) :)

示例:

Socket s = new Socket(...); // connect to server
BufferedReader br = new BufferedReader(s.getInputStream()); // creating a bufferedReader around the inputstream. If you're dealing with binary data, you shouldn't create a (Buffered)Reader
while (String line = br.readLine()) {
  //do something here
}

所以这是一个如何做到这一点的答案: (我写了一个完整的例子运行()客户端线程的方法

@Override
public void run() {
   while(client.isConnected()) {  //client.isConnected should be a method of your client class
      Object inputData = in.read(); //you should use a proper Object type here, if you
                                    //use InputStreamReader, it would be Byte and if you
                                    //use BufferedReader it would be String
      doCrazyStuff(inputData);      //just an example of manipulating data, do your own stuff here
   }
}

这里有一个 BufferedReader 的例子(我不会改变编码什么的,因为我认为这只是一个训练应用)

public void run() {
   while(client.isConnected()) {  //client.isConnected should be a method of your client class
      while(!in.ready()) { }        //here you CAN use the method ready, that is boolean

      String inputData = in.readLine();
      doCrazyStuff(inputData);      //just an example of manipulating data, do your own stuff here
   }
}