我正在尝试通过TcpClient
Networkstream
发送一种乒乓通信。
我有一个客户端,它向服务器发送连续数据,服务器必须通知客户端获得的数据,以便允许客户端再次发送一些信息。
(循环中)我的流程是这样的:
//循环
现在,一切正常,但是一旦我将所有数据发送到服务器,它就会跳过初始字节读取它们,为此,它将接收到的消息的最终字节填充为0。
注意:我需要保持连接打开状态,所以不能每次都关闭打开。
这是我的代码,我删除了几行以使其更具可读性:
客户端代码(相关)
using(var clientStream = client.GetStream()){
BinaryFormatter binaryFormatter = new BinaryFormatter();
while (client.Connected)
{
SerializableSharedObject sso = new SerializableSharedObject(connectionIdTest)
{
timeStamp = DateTime.Now,
customerCode = "TEST",
desktopCode = "DESK",
objectType = (int)SerializableObjectType.SCREEN,
screen = GrabDesktop() //a bitmap
};
byte[] ba = ObjectToByteArray(sso);
byte[] userDataLen = BitConverter.GetBytes((Int32)ba.Length);
//sending to server the next data length
clientStream.Write(userDataLen, 0, 4);
//waiting from server the confirmation that he received data length
bool lengthSent = false;
while (!lengthSent)
{
if (clientStream.DataAvailable)
{
byte[] sendResult = new byte[1];
if (clientStream.Read(sendResult, 0, 1) > 0)
{
if (sendResult[0] == (byte)1)
lengthSent = true;
}
}
}
//sending to server the whole data
clientStream.Write(ba, 0, ba.Length);
//waiting from server the confirmation of receiving whole data
bool contentSent = false;
while (!contentSent)
{
if (clientStream.DataAvailable)
{
byte[] sendResult = new byte[1];
if (clientStream.Read(sendResult, 0, 1) > 0)
{
if (sendResult[0] == (byte)1)
contentSent = true;
}
}
}
}
}
服务器端代码(相关)
using( var clientStream stream = client.GetStream())
{
while (client.Connected)
{
byte[] readMsgLen = new byte[4];
while (!clientStream.DataAvailable)
{
// wait for data...
}
// read the next data length
clientStream.Read(readMsgLen, 0, 4);
int dataLen = BitConverter.ToInt32(readMsgLen, 0);
byte[] readMsgData = new byte[dataLen];
//send to client the confirm message.
clientStream.Write(new byte[1] { (byte)1 }, 0, 1);
while (!clientStream.DataAvailable)
{
// wait for data...
}
// read the whole data
clientStream.Read(readMsgData, 0, dataLen); // <-- incomplete
}
}
我注意到最终从服务器读取的数据正在跳过。以发送244000(+/-)个字节为例,它跳过了前20个字节,并用bytes
个值填充了后20个0
。
我尝试调试了很多次,发现stream
似乎仅从“现在”读取字节,由于接收数据的延迟而丢失了发送的第一个字节。调试它跳过了200 bytes
,有一个断点,等待了几秒钟,跳过了数千。
如何使流读取从0 position
开始的每个字节?
我已经尝试实现BinaryReader
和BinaryWriter
,但是结果是相同的。
谢谢
Github仓库here