我有两个用 c# 编写的程序,一个使用 networkStream.beginWrite 命令发送以下内容:
1,2,3,4,5......200,201,202...(一些终止字节数组)
现在,我让另一个程序获取字节,由于某种原因它读取的第一件事是:
197, 198, 199....(终端数组)
我的问题是,为什么我的 TCP beginWrite 发送它(缓冲区)乱序?
另外,对于一些背景信息,我正在使用 beginReceive 在另一边阅读它。此外,我发送的字节数组是 30000 字节长,我正在将它读入另一台计算机的 1024 字节缓冲区。如果我这样做并使用终止数组拆分它会不会有问题?
这是我在计算机 1 上的发送命令:
public bool sendToServer(SocketAsyncEventArgs e, params byte[][] buffer)
{
int length = 0;
foreach (byte[] bytes in buffer)
{
length += bytes.Length;
}
byte[] buffer2 = new byte[length + 5];
int index = 0;
foreach (byte[] bytes in buffer)
{
Buffer.BlockCopy(bytes, 0, buffer2, index, bytes.Length);
index += bytes.Length;
}
byte[] eof = { 60, 69, 79, 70, 62 };
Buffer.BlockCopy(eof, 0, buffer2, index, 5);
// netStream.Write(buffer2, 0, buffer2.Length);
netStream.BeginWrite(buffer2, 0, buffer2.Length, new AsyncCallback(SendCallback), clientSocket);
//socketEventArg.SetBuffer(buffer2, 0, buffer2.Length);
//Socket sock = socketEventArg.UserToken as Socket;
//bool willRaiseEvent = sock.SendAsync(socketEventArg);
Console.WriteLine("Sending: " + buffer2.Length + " bytes of data");
//foreach (byte bi in buffer2)
{
// Console.WriteLine(bi);
}
// clientSocket.BeginSend(buffer2, 0, buffer2.Length, 0,
// new AsyncCallback(SendCallback), clientSocket);
return true;
}
这是我接收该数据的代码:
public void AcceptCallback(IAsyncResult ar)
{
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
Console.WriteLine("Connected!");
// Create the state object.
MonkeyObject state = new MonkeyObject();
state.workSocket = handler;
MonkeyObjects.Add(state);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
byte[] buffer = new byte[1024];
state.currentBuffer = buffer;
handler.BeginReceive(buffer, 0, MonkeyObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}