Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.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
C# TCP流套接字数据接收_C#_Sockets_Windows Phone 8_Tcp_Stream Socket Client - Fatal编程技术网

C# TCP流套接字数据接收

C# TCP流套接字数据接收,c#,sockets,windows-phone-8,tcp,stream-socket-client,C#,Sockets,Windows Phone 8,Tcp,Stream Socket Client,我在Windows上编写了一个使用TCP套接字的服务器-客户端通信,它工作正常,但现在我正尝试将客户端移植到Windows Phone,但我确实在数据接收方面遇到了困难。我正在使用StreamSocket,因此我需要知道数据的长度。例如: DataReader dataReader = new DataReader(clientSocket.InputStream); uint bytesRead = 0; bytesRead = await dataReader.LoadAsync(Siz

我在Windows上编写了一个使用TCP套接字的服务器-客户端通信,它工作正常,但现在我正尝试将客户端移植到Windows Phone,但我确实在数据接收方面遇到了困难。我正在使用StreamSocket,因此我需要知道数据的长度。例如:

DataReader dataReader = new DataReader(clientSocket.InputStream);

uint bytesRead = 0;

bytesRead = await dataReader.LoadAsync(SizeOfTheData); // Here i should write the size of data, but how can I get it? 

if (bytesRead == 0)
    return;

byte[] data = new byte[bytesRead];

dataReader.ReadBytes(data);
我尝试在服务器端执行此操作,但我认为这不是一个好的解决方案:

byte[] data = SomeData();

byte[] length = System.Text.Encoding.ASCII.GetBytes(data.Length.ToString());

// Send the length of the data
serverSocket.Send(length);
// Send the data
serverSocket.Send(data);

因此,我的问题是,如何在同一个数据包中发送长度和数据,以及如何在客户端正确处理它?

处理这一问题的常用技术是用数据的长度预先处理数据。例如,如果要发送100个字节,请将数字“100”编码为四字节整数(或两字节整数…由您决定),并将其固定在缓冲区的前面。因此,您将实际传输104个字节,前四个字节表示后面有100个字节。在接收端,您将读取前四个字节,这表示您需要读取额外的100个字节。有道理吗

随着协议的发展,您可能会发现需要不同类型的消息。因此,除了四字节长度外,还可以添加一个四字节消息类型字段。这将向接收方指定正在传输的消息类型,长度指示该消息的长度

byte[] data   = SomeData();
byte[] length = System.BitConverter.GetBytes(data.Length);
byte[] buffer = new byte[data.Length + length.Length];
int offset = 0;

// Encode the length into the buffer.
System.Buffer.BlockCopy(length, 0, buffer, offset, length.Length);
offset += length.Length;

// Encode the data into the buffer.
System.Buffer.BlockCopy(data, 0, buffer, offset, data.Length);
offset += data.Length;  // included only for symmetry

// Initialize your socket connection.
System.Net.Sockets.TcpClient client = new ...;

// Get the stream.
System.Net.Sockets.NetworkStream stream = client.GetStream();

// Send your data.
stream.Write(buffer, 0, buffer.Length);

谢谢你的回答,但我真的不明白你的意思。我知道我的英语不太好,对此我深表歉意,但你能提供一个你想法的示例代码吗?@David,添加了一些代码,用数据对长度进行编码并发送。希望这有帮助。请使用
BitConverter.GetBytes
而不是
ASCII.GetBytes
(这样,int(data.Length.)将始终获得4个字节)