c#使用Tcp协议的Socket Stream

时间:2016-08-14 13:07:40

标签: c# sockets tcp

我正在使用Socket Stream,协议Tcp用于服务器和客户端之间的连接 与外部IP地址。 我的问题是我没有收到客户发送的完整数据! 我试图解决许多解决方案,我知道我必须发送Data Size首先发送Actual Data,这就是我所做的例如:

string Data = ""; // my data here 
string Crypted = crypt(Data); // just a method crypting string (work perfectly tested)
byte[] DataBytes = Encoding.Unicode.GetBytes(Crypted);
_ClientSocket.Send(BitConverter.GetBytes(DataBytes.Length),0,4,0);
_ClientSocket.Send(DataBytes,0,DataBytes.Length,0);

接受Somethign喜欢那样:

 byte[] uffer;
            byte[] BufferData;
            int Size;
            int Received;
            uffer = new byte[4];
            while (true)
            {
                uffer = new byte[4];
                Size = _Client.Receive(uffer, 0, 4, 0);
                if (Size > 0)
                {
                    if (Size < _Client.ReceiveBufferSize)
                    {
                        BufferData = new byte[Size];
                    }
                    else
                    {
                        BufferData = new byte[_Client.ReceiveBufferSize];

                    }
                    Received = _Client.Receive(BufferData, 0, BufferData.Length, 0);
                    string Msg = Encoding.Unicode.GetString(buffer);
                    String Data = U.Decrypt(Msg);

                }

但我仍然不接收数据,如果我没有收到数据!

1 个答案:

答案 0 :(得分:1)

我认为你把第一次收到的结果和收到的价值混在一起。

后:

Size = _Client.Receive(uffer, 0, 4, 0);

Size将是该API调用接收的字节数,但是在您使用它来调整主内容的缓冲区大小之后。

您需要将uffer的内容转换为int并使用它来调整缓冲区的大小以便下次接收。 IE浏览器。你错过了一个:

int messageSize = BitConverter.ToInt32(uffer, 0);
BufferData = new byte [Math.Min(messageSize, _Client.ReceiveBufferSize];
相关问题