由Tcpclient-Tcpserver接收的帧的第二个字节数组变为负响应字节长度= 347713

时间:2015-10-25 11:25:55

标签: c# bytearray bytebuffer tcpserver receiver

请帮助我理解为什么当通过网络发送一些帧转换字节数组时,第一帧(字节数组)正确到达, 而到达的第二个字节数组(第二个帧)的大小错误甚至是负数。

这是发送帧的客户端代码:

public static void invia(byte[] bytetosend)
{
    byte[] compressed;
    compressed = Compressor.Compressor.Compress(bytetosend);

    byte[] bytes = new byte[1024];

    try
    {
        IPAddress ipAddressremoto = IPAddress.Parse("192.168.1.191");
        IPEndPoint remoteEP = new IPEndPoint(ipAddressremoto, 8585);
        try
        {
            if (Form1.z == 0)
            {
                Form1.client = new TcpClient();
                Form1.client.Connect(remoteEP);
                Form1.streamclient = client.GetStream();
                Form1.z = 1;
            }
            Form1.streamclient.Flush();
            byte[] sizePacket = new byte[50];
            sizePacket = BitConverter.GetBytes(compressed.Length);
            System.Console.WriteLine("size of packet = " + sizePacket.Length + " compressed.Length = " + compressed.Length + " " + "size inside packet " + BitConverter.ToInt32(sizePacket, 0));
            byte[] requestWithHeader = new byte[sizePacket.Length + compressed.Length];
            sizePacket.CopyTo(requestWithHeader, 0);
            bytetosend.CopyTo(requestWithHeader, sizePacket.Length);
            streamclient.Write(requestWithHeader, 0, requestWithHeader.Length);
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException : {0}", se.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Unexpected exception : {0}", e.ToString());
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

这是接收帧的服务器端代码,不幸的是我得到了正确的, 正确尺寸框架只有第一个但不是第二个框架 注意:描述了一些旧指令而不是删除

public WindowsFormsServer()
{
    var frameTask = Task.Factory.StartNew(() =>
    {
        try
        {
            while (true) 
            {
                if (WindowsFormsServer.y == 0)
                {
                    WindowsFormsServer.server = WindowsFormsServer.Idea_server();
                    // WindowsFormsServer.server.ReceiveTimeout = 50000;
                    //          Console.WriteLine("Waiting for a connection...");
                    WindowsFormsServer.streamserver = server.GetStream();
                }
                //streamserver.Flush();

                byte[] responseBytes = null;

                //if (streamserver.CanRead)
                //{
                    var responseStream = new System.IO.MemoryStream();
                    byte[] sizePacket = new byte[50];

                    streamserver.Read(sizePacket, 0, sizePacket.Length);
                    int responseLength = BitConverter.ToInt32(sizePacket, 0);
                    System.Console.WriteLine("size of packet = " + sizePacket.Length + "size inside packet = " + responseLength);
                    byte[] response = new byte[responseLength];

                    int bytesReceived = 0;
                    while (bytesReceived < responseLength)
                    {
                        int bytesRead = streamserver.Read(response, bytesReceived, responseLength - bytesReceived);
                        bytesReceived += bytesRead;
                    }
                    System.Console.WriteLine("frameTask attivo \r\n");
                    responseStream.Write(response, 0, responseLength);
                    //System.Threading.Thread.Sleep(1); //added this line
                    responseBytes = responseStream.ToArray();
                    Console.WriteLine("responseBytes Length = " + responseBytes.Length);
                //}
            }
        }
        catch (NullReferenceException ex) 
        { 
            System.Console.WriteLine("Errore: " + ex.ToString()); 
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        try
        {
            //MessageData.Picture2 = (Bitmap)byteArrayToImage(Compressor.Compressor.Decompress(responseBytes));
            MessageData.Picture2 = (Bitmap)byteArrayToImage(responseBytes);
            CamImageBox.Image = MessageData.Picture2;
        }
        catch (NullReferenceException ex)
        {
            System.Console.WriteLine("Errore: " + ex.ToString());
        }
        catch (Exception ex)
        {
            System.Console.WriteLine("Errore: " + ex.ToString());
        }

    });
    //frameTask.Start();
    InitializeComponent();
}

这是服务器端的错误,它将帧作为字节数组接收

'WindowsFormsServer.vshost.exe' (CLR v4.0.30319: WindowsFormsServer.vshost.exe): caricamento di 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll' completato. Caricamento dei simboli ignorato. Il modulo è ottimizzato e l'opzione del debugger 'Solo codice utente' è abilitata.
lunghezza = 5

这是使用HEADER编写客户端SENDE BYTI ARRAY FRAME的大小的课程的长度,然后我阅读服务器端接收器

inviocomandoTask attivo 
  • 包的大小= 50
  • 包内的尺寸= 347713

这是收到的第一帧的长度,它是正确的,因为它与发件人发送的相同。

'WindowsFormsServer.vshost.exe' (CLR v4.0.30319: WindowsFormsServer.vshost.exe): caricamento di 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_it_b77a5c561934e089\mscorlib.resources.dll' completato. Modulo compilato senza simboli.

frameTask attivo

  • responseBytes Length = 347713
  • 包的大小= 50
  • 包内的尺寸= -383988050

这是收到的第二帧的长度,这是错误的

Eccezione generata: 'System.OverflowException' in WindowsFormsServer.exe
Eccezione generata: 'System.ArgumentNullException' in mscorlib.dll
System.OverflowException: Le dimensioni della matrice hanno superato l'intervallo supportato. The size of the array exceeded the supported range.
   in WindowsFormsServer.WindowsFormsServer.<.ctor>b__12_0() in C:\Users\vmtest\Documents\CamDisplay4\WindowsFormsServer\Form1.cs:riga 70
Errore: System.ArgumentNullException: Il buffer non può essere null.
Nome parametro: buffer
   in System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable)
   in WindowsFormsServer.WindowsFormsServer.byteArrayToImage(Byte[] bytesArr) in C:\Users\vmtest\Documents\CamDisplay4\WindowsFormsServer\Form1.cs:riga 170
   in WindowsFormsServer.WindowsFormsServer.<.ctor>b__12_0() in C:\Users\vmtest\Documents\CamDisplay4\WindowsFormsServer\Form1.cs:riga 98
Il thread 0x19ec è terminato con il codice 0 (0x0).
Il thread 0x19d4 è terminato con il codice 0 (0x0).
Il programma '[1352] WindowsFormsServer.vshost.exe' è terminato con il codice 0 (0x0).

您对收到的第二帧字节数组中发生了什么有建议吗?* 您是否认为它是由服务器引起的,它在没有ASYNC方法的情况下以同步模式接收字节?

2 个答案:

答案 0 :(得分:0)

byte[] sizePacket = new byte[50];
streamserver.Read(sizePacket, 0, sizePacket.Length);

这里,您只读取50个字节,但仅使用前4个字节。其余的都被扔掉了。

我会这样做:

var br = new BinaryReader(someStream);
var length = br.ReadUInt32();
var contents = br.ReadBytes(length);

这就是你真正需要的一切。

        byte[] sizePacket = new byte[50];
        sizePacket = BitConverter.GetBytes(compressed.Length);

为什么总是50个字节?这毫无意义。首先使用正确的长度。在这里,你要覆盖那个变量,所以这应该是:

        byte[] sizePacket = BitConverter.GetBytes(compressed.Length);
System.Console.WriteLine("size of packet = " + sizePacket.Length + "size inside packet = " + responseLength);

这条消息是假的。这不是“数据包”的大小。 TCP不会公开数据包。数组大小为50,读取Read的返回值可能与50不同。

答案 1 :(得分:0)

现在我改变了你所说的代码: 但是我觉得它不正确并且可以改进,实际上接收器部分我需要设置帧大小,当我在接收帧之前创建字节数组时,所以我做到了:

                        var br = new BinaryReader(streamserver);
                        var length = br.ReadUInt32();
                        var responseLength = br.ReadBytes(4);
                        int responseIntLength = BitConverter.ToInt32(responseLength, 0);
                        byte[] response = new byte[responseIntLength];

这是新的全服务器接收器tcp端

    public WindowsFormsServer()
    {
        var frameTask = Task.Factory.StartNew(() =>
        {

            try
            {
                while (true) 
                {
                        if (WindowsFormsServer.y == 0)
                        {
                            WindowsFormsServer.server = WindowsFormsServer.Idea_server();
                            // WindowsFormsServer.server.ReceiveTimeout = 50000;
                            //          Console.WriteLine("Waiting for a connection...");
                            WindowsFormsServer.streamserver = server.GetStream();
                        }
                        //streamserver.Flush();

                        byte[] responseBytes = null;

                        //if (streamserver.CanRead)
                        //{
                            var responseStream = new System.IO.MemoryStream();
                            byte[] sizePacket = new byte[4];

                            var br = new BinaryReader(streamserver);
                            var length = br.ReadUInt32();
                            var responseLength = br.ReadBytes(4);
                            int responseIntLength = BitConverter.ToInt32(responseLength, 0);
                            byte[] response = new byte[responseIntLength];
                            System.Console.WriteLine("size inside responseIntLength = " + responseLength);

                            int bytesReceived = 0;
                            while (bytesReceived < responseIntLength)
                            {
                                int bytesRead = streamserver.Read(response, bytesReceived, responseIntLength - bytesReceived);
                                bytesReceived += bytesRead;
                            }
                            System.Console.WriteLine("frameTask attivo \r\n");
                            responseStream.Write(response, 0, responseIntLength);
                            //System.Threading.Thread.Sleep(1); //added this line
                            responseBytes = responseStream.ToArray();
                            Console.WriteLine("responseBytes Length = " + responseBytes.Length);
                        //}
                }
            }
            catch (NullReferenceException ex) 
            { 
                System.Console.WriteLine("Errore: " + ex.ToString()); 
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            try
            {
                //MessageData.Picture2 = (Bitmap)byteArrayToImage(Compressor.Compressor.Decompress(responseBytes));
                MessageData.Picture2 = (Bitmap)byteArrayToImage(responseBytes);
                CamImageBox.Image = MessageData.Picture2;
            }
            catch (NullReferenceException ex)
            {
                System.Console.WriteLine("Errore: " + ex.ToString());
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Errore: " + ex.ToString());
            }

        });
        //frameTask.Start();
        InitializeComponent();
    }