TCPIP异步服务器连接丢失

时间:2015-05-26 00:13:03

标签: c# asynchronous tcp server

我已为tcpip服务器编写(复制)代码。 我们有通过TCPIP发送消息的软件,并期望返回消息,表示接收已确认。这很好用。但在发送确认后,连接就会丢失。我不知道代码在哪里发生这种丢失。因此,当发送下一条消息时,没有连接,因此它会进行回滚并再次重新连接,然后发送消息。因此每次我发送多条消息时,我都会收到回滚警报。我们将不断整天发送消息。以下是代码:

class Program
{
    // State object for reading client data asynchronously
    public class StateObject
    {
        // Client  socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 1024;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }

    public class AsynchronousSocketListener
    {
        // Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public AsynchronousSocketListener()
        {
        }
        public static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // The DNS name of the computer
            // running the listener is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);

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

            // Bind the socket to the local endpoint and listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    Console.WriteLine("Waiting for a connection...");
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }

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

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();

        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();
            ar.AsyncWaitHandle.WaitOne(100);

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;
            String s1 = "MSH|^~\\&|BB|NSCCH|MILLENNIUM|BB|20150522080258137||ACK";
            String s2 = "|20150522080258137883|P|2.4";//\r\nMSA|AA|Q245548634T287475114";
            //String s3 = String.Empty;
            String s4 = "MSA|AA|Q245548634T287475114";
            //string s5 = "0x02";
            int value = Convert.ToInt32("0x1C", 16);
            char cc = (char)value;
            int value_eob = Convert.ToInt32("0x0b", 16);
            char eob = (char)value_eob;
            int value_eod = Convert.ToInt32("0x0D", 16);
            char eod = (char)value_eod;
            int value_eoa = Convert.ToInt32("0x0A", 16);
            char eoa = (char)value_eoa;

            /*StringBuilder sb1 = new StringBuilder(s5);
            sb1.Append(s1);
            sb1.Append(s2);
            s3 = sb1.ToString();*/

            //byte[] s4 = Encoding.ASCII.GetBytes(s3);
            // 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);

            if (bytesRead > 0)
            {
                // 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();
                //s3 = state.sb.ToString();


                // s3 = s1.ToString() + s2.ToString();
                if (bytesRead < 1024) //content.IndexOf("<EOF>") > -1)
                {

                    string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";

                    // All the data has been read from the 
                    // client. Display it on the console.
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        content.Length, content);
                    Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
                        s6.Length, s6);
                    // Echo the data back to the client.
                    Send(handler, s6);

                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
                }
            }
            else
            {
                if (content.Length > 0)
                {
                    string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";

                    // All the data has been read from the 
                    // client. Display it on the console.
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                        content.Length, content);
                    Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
                        s6.Length, s6);
                    // Echo the data back to the client.
                    Send(handler, s6);

                }
            }

//添加了代码                     handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,                         新的AsyncCallback(ReadCallback),state);             }

        private static void Send(Socket handler, String data)
        {
            // Convert the string data to byte data using ASCII encoding.
            byte[] byteData = Encoding.ASCII.GetBytes(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());
            }
        }

        public static int Main(string[] args)
        {
            StartListening();
            return 0;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您的代码中至少有两个主要错误:

  1. 您假设接收操作将始终在填充提供的缓冲区时完成,除非客户端已停止发送数据(即此时不再接收数据)。这通常是正确的,但保证,如果它做出这样的假设,你的代码将会虚假地失败。
  2. 一旦您认为自己已收到客户端的所有当前传输,就不会再次呼叫BeginReceive()。从那时起,这使得连接完全失效。
  3. 另一个可能的错误是:

    1. 您的代码未正确分区传输的数据。这里似乎没有任何代码能够可靠地检测接收到的字节流中两个不同逻辑消息之间的边界。根据客户端发送数据的速度,有可能将某些或所有数据作为后续逻辑消息的一部分作为早期逻辑消息的一部分使用。
    2. 不幸的是,您的问题中没有提供足够的精确细节。短语&#34;连接退出&#34;是非特定的,没有明确的技术含义。这可能意味着您在套接字上出现错误,或者它可能只是意味着您从未收到任何更多数据,或者它可能完全意味着其他内容。

      那就是说,如果你的意思是&#34;永远不会收到更多的数据&#34;,那么我会说上面的#2错误很可能是你问题的根本原因。当然,#1错误可以与#2错误一起导致&#34;永远不会再收到任何数据&#34;。

      没有a good, minimal, complete code example可靠地重现问题(请注意,对于与网络相关的问题,一个完整的示例包括连接的两个端点),无法确定所有的错误代码示例,不要介意实际问题是什么。但是,我建议修复上面的错误,看看是否有所改善。

      作为一般规则,您的网络代码应如下运行:

      • 接收数据
      • 解释数据,识别逻辑消息边界(如果有)
      • 如果收到完整的逻辑消息,请进行处理。 确保保留可能已收到的任何多余数据,以便作为下一条逻辑消息的一部分进行处理。
      • 继续上述操作,在处理完当前操作的结果后,始终启动新的接收操作,直到接收操作完成,字节数为零。
      • 当零字节接收操作完成时,完成对到目前为止收到的数据的处理(如果还没有处理),并通过发送任何剩余数据(如果有的话)并调用{{}来确认连接的正常关闭。 1}}和只有调用Socket.Shutdown(SocketShutdown.Both)来实际关闭套接字。