C#tcp客户端服务器不';不要总是发送完整的数据

C#tcp客户端服务器不';不要总是发送完整的数据,c#,tcp,server,client,byte,C#,Tcp,Server,Client,Byte,我目前正在使用TCP客户端和服务器。最近,我为消息添加了加密,没有任何问题。一旦我开始注意到我遇到了这样一个奇怪的错误: 但这完全是随机的,不知道为什么。它发生在更大的消息中,但正如我所说的,并不总是如此 在服务器端检查byte[]长度时显示1920(有时在客户端也显示1920,这就是我没有错误的时候) 在客户方面,它说的要少得多 我实际上认为,有时候客户端没有收到它应该接收的完整字节,我就是这样做的: 客户: byte[] bb = new byte[12288]; int k = stm

我目前正在使用TCP客户端和服务器。最近,我为消息添加了加密,没有任何问题。一旦我开始注意到我遇到了这样一个奇怪的错误:

但这完全是随机的,不知道为什么。它发生在更大的消息中,但正如我所说的,并不总是如此

在服务器端检查byte[]长度时显示1920(有时在客户端也显示1920,这就是我没有错误的时候)

在客户方面,它说的要少得多

我实际上认为,有时候客户端没有收到它应该接收的完整字节,我就是这样做的:

客户:

byte[] bb = new byte[12288];
int k = stm.Read(bb, 0, 12288);
string message = Encoding.UTF8.GetString(bb, 0, k);
MessageBox.Show(message.Length.ToString()); // This sometimes says 1460, and 1920
message = Encrypter.DecryptData(message); // Error here If the length is not 1920
服务器:

bmsg = Encrypter.EncryptData(((int)Codes.XYZEnum) + "=" + data);
Logger.Log(bmsg.Length.ToString()); // Original msg, always says 1920
s.Send(asen.GetBytes(bmsg));
s.Close();
有什么问题吗?我应该尝试异步发送吗

解决方案:

服务器代码,我花了一点时间使其变酷:

System.Net.Sockets.Socket s = myList.AcceptSocket(); // Accept the connection

Stream stream = new NetworkStream(s); // Create the stream object
byte[] leng = new byte[4]; // We will put the length of the upcoming message in a 4 length array
int k2 = s.Receive(leng); // Receive the upcoming message length
if (BitConverter.IsLittleEndian)
{
    Array.Reverse(leng);
}
int upcominglength = (BitConverter.ToInt32(leng, 0)); // Convert it to int

byte[] b = ByteReader(upcominglength, stream); // Create the space for the bigger message, read all bytes until the received length!

string message = Encoding.UTF8.GetString(b, 0, b.Length); // Convert it to string!


internal byte[] ByteReader(int length, Stream stream)
{
    byte[] data = new byte[length];
    using (MemoryStream ms = new MemoryStream())
    {
        int numBytesRead;
        int numBytesReadsofar = 0;
        while (true)
        {
            numBytesRead = stream.Read(data, 0, data.Length);
            numBytesReadsofar += numBytesRead;
            ms.Write(data, 0, numBytesRead);
            if (numBytesReadsofar == length)
            {
                break;
            }
        }
        return ms.ToArray();
    }
}
客户端代码,并且运行良好!:

var result = tcpclnt.BeginConnect(User.IP, User.Port, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3)); // Connect with timeout

if (!success)
{
    return "Failed to connect!";
}
Stream stm = tcpclnt.GetStream(); // get the stream

UTF8Encoding asen = new UTF8Encoding();

byte[] ba = asen.GetBytes(msg); // get the bytes of the message we are sending
byte[] intBytes = BitConverter.GetBytes(ba.Length); // Get the length of that in bytes
if (BitConverter.IsLittleEndian)
{
    Array.Reverse(intBytes);
}

stm.Write(intBytes, 0, intBytes.Length); // Write the length in the stream!
stm.Flush(); // Clear the buffer!
stm.Write(ba, 0, ba.Length); // Write the message we are sending!

// If we have answers....
byte[] bb = new byte[10000];
int k = stm.Read(bb, 0, 10000);
string mmessage = Encoding.UTF8.GetString(bb, 0, k);
// If we have answers....


tcpclnt.Close(); // Close the socket

因为一次只能发送8Kb的数据包。如果您有大数据,则需要使用循环