C#TCPClient-Server并不总是发送完整数据

时间:2016-08-04 08:35:57

标签: c# tcp server client byte

我目前正在开发TCPClient和Server。最近我为邮件添加了加密功能,并没有遇到任何问题。一旦我开始注意到我得到了这样一个奇怪的错误:

Error

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

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

在客户端,它说的要少得多。

Weird crap

我实际上认为有时客户端没有收到它应该的完整字节,这就是我的工作方式:

客户端:

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();

可能是什么问题?我应该尝试异步发送吗?

SOLUTION:

服务器代码,花了我一点时间让它变得很酷:

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

1 个答案:

答案 0 :(得分:2)

因为只有8Kb可以通过一次包发送。如果您有大量数据,则需要使用循环。