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

时间:2015-01-02 15:22:43

标签: java sockets

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

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

InputStream类的available()方法是否可以完成这项工作? 代码:

 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类作为动态字节数组 是否有任何java等效的MemoryStream
我可以在java中做这样的事情: 伪码

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

我很抱歉,但我是java的新人

3 个答案:

答案 0 :(得分:2)

不,可用的用法不是很有用,因为它不能像你期望的那样工作。只需使用in.read()。它会等到服务器发出某些事情。因此,如果您在一个线程中使用它,它只是等待直到可以收到某些东西。

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

答案 1 :(得分:2)

示例:

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
}

答案 2 :(得分:1)

所以这是一个答案,你可以这样做: (我写了一个客户端线程的完整示例run()方法

@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
   }
}