接收的字节数与i';m发送-c#套接字
我的项目有一个奇怪的问题: im使用套接字,服务器/客户端代码是相同的,它们都使用两个不同的线程(一个发送线程,一个接收线程),但im获取的数据不是im发送的数据 发送:接收的字节数与i';m发送-c#套接字,c#,sockets,C#,Sockets,我的项目有一个奇怪的问题: im使用套接字,服务器/客户端代码是相同的,它们都使用两个不同的线程(一个发送线程,一个接收线程),但im获取的数据不是im发送的数据 发送: double[] data = new double[3]; // i'm sending this double array, in the actual code it's filled with 3 numbers byte[] result = new byte[data.Length * sizeof(doubl
double[] data = new double[3];
// i'm sending this double array, in the actual code it's filled with 3 numbers
byte[] result = new byte[data.Length * sizeof(double)];
Buffer.BlockCopy(data, 0, result, 0, result.Length);
// converting to byte
clientSocket.Send(result);
// at this point, the array size is 24 bytes (the size doesnt change for every time i'm trying to send) and i'm sending it to the client/server.
接收:
byte[] bytes = BitConverter.GetBytes(clientSocket.Receive(b, SocketFlags.None));
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
// receiving the data, buffer size is 1024
double[] values = new double[bytes.Length / 8];
for (int i = 0; i < values.Length; i++)
values[i] = BitConverter.ToDouble(bytes, i * 8);
// converting back to double[]
this.receivingData = values;
// bytes is an array with only 4 bytes and receivingData is a double array filled with nothing. (this happens every time im receiving data and the bytes values is allways the same)
byte[]bytes=BitConverter.GetBytes(clientSocket.Receive(b,SocketFlags.None));
if(位转换器.IsLittleEndian)
Array.Reverse(字节);
//接收数据时,缓冲区大小为1024
double[]值=新的double[bytes.Length/8];
for(int i=0;i
起初我认为转换为double[]有问题,所以我尝试了不同的方法,但结果都是一样的
我缺少什么?Receive返回接收的字节数。如果收到的字节数少于通知的字节数,则需要正确处理,例如,循环直到收到必要的字节数。下面是在流的情况下如何做到这一点,您可以尝试类似的方法 此外,在这种情况下,您需要确保以相同的电子邮件发送/接收号码,我希望您已经这样做了
注:正如评论中提到的,您似乎也没有正确使用
Receive
。Socket.Receive
将接收到的字节复制到作为参数传递给它的字节数组中。您将获得该方法返回的整数的字节数,即接收到的字节数。您应该在这里使用b
而不是bytes
。您可能应该用BinaryReader/Writer替换所有这些,包括损坏的数组反转。它处理部分读取(您不需要)和endianness。您的抽象级别太低。你想发送双倍,而不是混乱的字节。在实际中,它是一个无休止的循环,有更多的细节,我只是想告诉你我的想法。您是对的,我已将缓冲区大小更改为24,并从中构建接收的双数组,而不是从方法接收输出。业余的错误。。