我通过 LAN 网络发送序列化数据,但有时信息会丢失!过程如下:
发件人:
string mydata
正在序列化string mydata
被转换为byte[] bytes_of_mydata
int size_of_mydata
是长度byte[] bytes_of_mydata
int size_of_mydata
本身就变成了byte[] bytes_size_of_mydata
byte[] bytes_of_mydata
并被byte[] bytes_size_of_mydata
发送
接收者:
- 我先收到
byte[] bytes_size_of_mydata
int size_of_mydata
检索第二条消息的长度byte[] bytes_size_of_mydata
- 然后我收到
byte[] bytes_of_mydata
,知道确切的长度! - 然后我转换
byte[] bytes_of_mydata
为string mydata
- 反序列化
string mydata
这种方法通常适用于大多数情况,但有时我的数据没有完全传输,因此无法反序列化字符串。
我已经byte[]
在“接收器”上调试了收到的内容,这就是发生的事情:
我得到第二条消息的大小:
int size_of_second_message = BitConverter.ToInt32(dataByteSize, 0); // 55185
我开始接收到字节数组的第二条消息:
Byte[] dataByte = new Byte[55185];
但是从位置 5840 开始,我开始收到 0(空值),所以“5840 - 55185”部分都是“0”:
byte[5836] = 53;
byte[5837] = 57;
byte[5838] = 54;
byte[5839] = 49;
byte[5840] = 0; // information ends to flow
byte[5841] = 0;
byte[5842] = 0;
byte[5843] = 0;
//....
byte[55185] = 0;
上面的示例取自实际的调试器!
所以有什么问题?这就像在传输过程中失去了连接!为什么会发生这种情况,我该如何解决这个问题?它不会发生在“每次”的基础上。
代码来了
发送:
//text_message - my original message
//Nw - network stream
MemoryStream Fs = new MemoryStream(ASCIIEncoding.Default.GetBytes(text_message));
Byte[] buffer = Fs.ToArray(); // total 55185 bytes (as in example)
Byte[] bufferSize = BitConverter.GetBytes(Fs.Length); // 32 bytes represent size
bufferSize = GetNewByteSize(bufferSize);
Nw.Write(bufferSize, 0, bufferSize.Length); // send size
Nw.Flush();
Nw.Write(buffer, 0, buffer.Length); // send message
Nw.Flush();
收到:
//get first(SIZE) bytes:
int ReadSize = 0; int maxSize = 32; // 32 - constant!
Byte[] dataByteSize = new Byte[maxSize];
int origsize;
using (var strm = new MemoryStream())
{
ReadSize = Nw.Read(dataByteSize, 0, maxSize);
strm.Write(dataByteSize, 0, ReadSize);
strm.Seek(0, SeekOrigin.Begin);
origsize = BitConverter.ToInt32(dataByteSize, 0); // origsize = 55185
}
Nw.Flush();
//get next(MESSAGE) bytes:
string message = ""; int thisRead = 0;
int max = Convert.ToInt32(origsize); // origsize = 55185
Byte[] dataByte = new Byte[max];
using (var strm = new MemoryStream())
{
thisRead = Nw.Read(dataByte, 0, max);
strm.Write(dataByte, 0, thisRead);
strm.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(strm))
{
message = reader.ReadToEnd();
}
}
Nw.Flush();
// message - the message that is being transmitted partly (sometimes)!
我不想发布代码,但你们通常会问“告诉我们你做了什么”,所以就在这里!
编辑
临时修复是切换到 StreamWriter,阅读器。
接收+发送(服务器):
NetworkStream Nw = new NetworkStream(handlerSocket.Client);
string toreceive = "";
StreamReader reader = new StreamReader(Nw);
toreceive = reader.ReadLine();
string text_message = "to send back";
StreamWriter writer = new StreamWriter(Nw);
writer.WriteLine(text_message);
writer.Flush();
Nw.Close();
发送+接收(客户端):
NetworkStream Nw = new NetworkStream(handlerSocket.Client);
StreamWriter writer = new StreamWriter(Nw);
writer.WriteLine("to send");
writer.Flush();
string toreceive = new StreamReader(Nw).ReadLine();
writer.Close();
Nw.Close();
我正在寻找有关原始问题的解决方案,但到目前为止,由于临时修复,一切正常。