Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从TCP套接字读取由特定delimeter分隔的数据_Java_Sockets_Tcp_Byte - Fatal编程技术网

Java 如何从TCP套接字读取由特定delimeter分隔的数据

Java 如何从TCP套接字读取由特定delimeter分隔的数据,java,sockets,tcp,byte,Java,Sockets,Tcp,Byte,我需要使用TCP上的套接字连接从服务器读取数据字节。数据是字节流的形式,由一个或多个值为255(0xFF)的八位字节分隔 我正在使用BufferedInputsRealm读取数据。我的部分代码如下: String messageString = ""; DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); byte[] bytes = new byte[16 * 10

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

我正在使用BufferedInputsRealm读取数据。我的部分代码如下:

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 = "";
      }
  }
String messageString=”“;
DataInputStream in=新的DataInputStream(新的BufferedInputStream(socket.getInputStream());
字节[]字节=新字节[16*1024];
System.out.println(“接收字节”);
while(true)
{
bytesRead=in.read(字节);
messageString+=新字符串(字节,0,字节读取);
如果()
{
System.out.println(“收到的消息:+messageString”);
//继续处理该消息
messageString=“”;
}
}
我需要IF条件,以便我知道我已收到一个数据包并开始处理相同的数据包。 我不知道我将要接收的消息的长度,我也不知道传入消息的长度

请帮助我读取这种类型的字节数据。
非常感谢您的帮助。

如果您的分隔符是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 = "";
}
bytesRead=in.read(字节);
int index=bytes.indexOf(255);
如果(索引)