C#TCP Socket Stream读取错误的字节

时间:2017-11-04 01:03:03

标签: c# sockets tcp stream

我用以下方式阅读流:

private Stream _Stream;
private Socket _Socket;//TCP Socket

private void ReadStream()
{
    if (Guest)
    {
        var sizeBuffer = ReadBytes(2);//the size buffer is always 2 
        int size = sizeBuffer[1];
        size |= (sizeBuffer[0] << 8);

        var data = ReadBytes(size);

        string payload = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
        var tokens = SplitPayload(payload);

        if (tokens[0] == "nick")
        {
            SetNick(tokens);
        }
        else
        {
            throw new ApplicationException("Set your nick first");
        }
    }
    else if(!Guest)
    {
        var sizeBuffer = ReadBytes(2);
        int size = sizeBuffer[1];
        size |= (sizeBuffer[0] << 8);

        var data = ReadBytes(size);

        string payload = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
        var tokens = SplitPayload(payload);

        CheckToken(tokens);
    }

    if (encrypted == null)
    {
        encrypted = false;
        byte[] sizebuffer = new byte[2];
        var size = _Socket.Receive(sizebuffer);
        byte[] data = new byte[size];
        var datasize = _Socket.Receive(data);
        if (data[0] == 0x01)
        {
            encrypted = true;
            _Stream = new NetworkStream(_Socket, true);
            var sslStream = new SslStream(_Stream, false);
            serverCertificate = new X509Certificate2(Path, "");
            sslStream.AuthenticateAsServer(serverCertificate);
            _Stream = sslStream;
        }
        else
        {
            encrypted = false;
            _Stream = new NetworkStream(_Socket, true);
        }
    }
}

我用:

写入流
private void SendServerMsg(string[] arguments)
{
    var msg = string.Join("\0", arguments);
    byte[] data = Encoding.UTF8.GetBytes(msg);
    byte[] sizeinfo = new byte[2];

    sizeinfo[1] = (byte)data.Length;
    sizeinfo[0] = (byte)(data.Length >> 8);

    _Stream.Write(sizeinfo, 0, sizeinfo.Length);
    _Stream.Write(data, 0, data.Length);
}

我的问题现在是: 1.当我在行

处创建一个断点时
_Stream.Write(sizeinfo, 0, sizeinfo.Length);

并逐步完成所有工作。 TCP _Socket获取正确的字节, 但没有断点,服务器卡在行

var data = ReadBytes(size);

并且大小超过5000但我发送的不超过15个字节(例如:&#34; nick \ 0test&#34;)

听说是readBytes方法

private byte[] ReadBytes(int count)
{
    byte[] buffer = new byte[count];
    for (var i = 0; i < count; i++)
    {
        var oneByte = _Stream.ReadByte();
        if (oneByte == -1)
        {
            break;
        }

        buffer[i] = (byte)oneByte;
    }
    return buffer;
}

0 个答案:

没有答案