通过网络发送更大的序列化对象会导致出现错误行为

时间:2016-06-05 02:51:18

标签: c# serialization network-programming bytearray packet-loss

我一直在努力通过网络为一个我正在研究的小项目序列化一个对象。我使用的代码几乎完美无缺,有时字节不能正确加载,但只需重新加载UI就可以解决这个问题。但是,在同一系统上进行通信时,只要您进入另一个系统,代码只能部分工作。一旦我尝试通过网络发送大小为30的字符串数组,服务器就会停止报告接收包,奇怪的是没有任何内容一致地抛出错误。一次又一次出现了一些错误:

System.InvalidOperationException: Cannot block a call on this socket while an earlier asynchronous call is in progress.
   at System.Net.Sockets.Socket.ValidateBlockingMode()
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode)
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.Socket.Receive(Byte[] buffer)
   at DMAssist.AsynchronousClient.Receive(Socket client) in C:\Users\crud4\documents\visual studio 2015\Projects\DMAssist\DMAssist\asyncsclient.cs:line 160
   at DMAssist.AsynchronousClient.StartClient(Object obj, Boolean expectresponse) in C:\Users\crud4\documents\visual studio 2015\Projects\DMAssist\DMAssist\asyncsclient.cs:line 119

这是我一直在控制台中遇到的主要错误,我不知道如何处理它。我在网络编程方面不是很有经验,所以我不知道自己哪里出错了。

我主要担心的是,由于某种原因,当客户端尝试发送超过330个字节时,服务器会停止报告接收字节,并导致整体故障行为。服务器肯定显示接收连接,但由于某种原因简单地立即杀死它。如果有人知道发生了什么或如何解决它,我将非常感谢帮助!

提前致谢!

客户端:

private netObject Receive(Socket client)
        {
            byte[] buffer = new byte[1024];
            int iRx = client.Receive(buffer);

            object rawbytes = ByteArrayToObject(buffer);
            netObject recvobject = (netObject)rawbytes;

            receiveDone.Set();

            return recvobject;
        }

public netObject StartClient(Object obj, bool expectresponse)
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the 
                // remote device is "host.contoso.com".
                IPAddress ipAddress = IPAddress.Parse(ip);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 25599);

                // Create a TCP/IP socket.
                Socket client = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, ObjectToByteArray(obj));
                sendDone.WaitOne();

                Send(client, Encoding.ASCII.GetBytes("<EOF>"));
                sendDone.WaitOne();


                // Receive the response from the remote device.
                if (expectresponse)
                {
                    netObject serverdata = Receive(client);
                    receiveDone.WaitOne();
                    return serverdata;
                }

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();

                return new netObject();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return new netObject();
            }
        }

private static void Send(Socket client, byte[] data)
        {

            byte[] byteData = data;

            // Begin sending the data to the remote device.
            client.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), client);
        }

服务器:

public void ReadCallback(IAsyncResult ar)
        {
            try {
                String content = String.Empty;

                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket. 
                int bytesRead = handler.EndReceive(ar);

                Console.WriteLine(bytesRead);

                if (bytesRead > 0)
                {
                    if (bytesRead != 5)
                    {
                        Array.Copy(state.buffer, state.cleanbuffer, bytesRead);
                    }

                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read 
                    // more data.
                    content = state.sb.ToString();

                    Console.WriteLine("SERVER: Recieved " + bytesRead + " bytes");

                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // All the data has been read from the 
                        // client. Display it on the console.


                        /*Console.WriteLine("Read {0} bytes from socket. Data : {1}",
                            content.Length, content);*/

                        object rawbytes = ByteArrayToObject(state.cleanbuffer);
                        netObject recvobject = (netObject)rawbytes;
                       }

                        // Echo the data back to the client.
                        Send(handler, ObjectToByteArray((object)recvobject));

                    }
                    else {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                    }
                }
            } catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

 private void Send(Socket handler, byte[] data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = data;

            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

1 个答案:

答案 0 :(得分:0)

好吧,经过一段时间的摸索后,我意识到我的客户端是异步和同步套接字的变种。所以,我将所有这些降级为同步,现在工作正常。回调有时会出现故障而不会进入下一个级别。