首页 文章

如何读取来自TCP Socket的数据由特定的分隔符分隔

提问于
浏览
0

我需要使用TCP上的Socket连接从服务器读取数据字节 . 数据采用字节流的形式,由一个或多个八位字节分隔,值为255(0xFF)

我使用BufferedInputSream来读取数据 . 我的代码的一部分如下:

String messageString = "";
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] bytes = new byte[16 * 1024];
System.out.println("Receiving Bytes");
  while(true)
  {
    bytesRead = in.read(bytes);
    messageString += new String(bytes,0,bytesRead);
    if (<SOME CONDITION TO KNOW THAT DELIMITER IS RECEIVED>)
      {
        System.out.println("Message Received: " + messageString);
        //Proceed to work with the message
        messageString = "";
      }
  }

我需要IF条件,以便我知道我收到了一个数据包并开始处理相同的数据包 . 我不知道我将收到的消息的长度,也不知道我在传入消息中的长度信息 .

请帮我读一下这种字节数据 . 真的很感激任何帮助 .

1 回答

  • 0

    如果您的分隔符是255,您只需检查刚刚读取的数据:

    bytesRead = in.read(bytes);
    int index= bytes.indexOf(255);
    if (index<0)
    {
        messageString += new String(bytes,0,bytesRead);
    }
    else //<SOME CONDITION TO KNOW THAT DELIMITER IS RECEIVED>)
    {
        messageString += new String(bytes,0,index);
        System.out.println("Message Received: " + messageString);
        //Proceed to work with the message
        messageString = "";
    }
    

相关问题