关于socket 通讯传送序例化对象时的边界问题

解决方案 »

  1.   


    public static byte[] Get_SendBytes(Byte[] SendValue)
    {
    Byte[] Resualt = new Byte[4 + SendValue.Length];
    Byte[] IntHead = MyConvert.int2bytes(SendValue.Length);
    int i = 0;
    for (; i < 4; i++)
    {
    Resualt[i] = IntHead[i];
    }
    for (; i < (4 + SendValue.Length); i++)
    {
    Resualt[i] = SendValue[i - 4];
    }
    return Resualt;
    }
      

  2.   


    byte[] tempbyte = new byte[4]; state.workSocket.Receive(tempbyte, 4, 0);
    state.BufferSize = MyConvert.bytes2int(tempbyte);
    state.buffer = new byte[state.BufferSize];
      

  3.   

    唔……大体意思就是先读4位的int,然后根据int继续读实际长度。
      

  4.   

    边界问题比较麻烦,在正常情况下可以通过发送包长获取边界。但也可能TCP/IP通道发生异常,比如6楼所说如果这4位不是在头部的时候,就出错了;这时需要对应的处理机制。最简单的发现出错,断开TCP/IP连接,重新发送,因此服务端需缓冲发送数据包,当收到客户端正常接收信号才清除。