C# 套接字错误10054:错误处理问题

C# 套接字错误10054:错误处理问题,c#,error-handling,tcp-ip,C#,Error Handling,Tcp Ip,每个人 如何解决错误代码10054?关于这一错误有很多问题。这是我的完整通信源代码。我想知道我的代码是否正确 WSAECONNRESET10054对等方重置连接。现有连接 被远程主机强制关闭。如果 远程主机上的对等应用程序突然停止,主机处于 重新启动,主机或远程网络接口被禁用,或者 远程主机使用硬关闭(有关详细信息,请参阅setsockopt) 远程套接字上的SO_LINGER选项)。也可能导致此错误 如果由于检测到“保持活动”活动而断开连接 一个或多个操作正在进行时发生故障。操作 正在使用WS

每个人

如何解决错误代码10054?关于这一错误有很多问题。这是我的完整通信源代码。我想知道我的代码是否正确

WSAECONNRESET10054对等方重置连接。现有连接 被远程主机强制关闭。如果 远程主机上的对等应用程序突然停止,主机处于 重新启动,主机或远程网络接口被禁用,或者 远程主机使用硬关闭(有关详细信息,请参阅setsockopt) 远程套接字上的SO_LINGER选项)。也可能导致此错误 如果由于检测到“保持活动”活动而断开连接 一个或多个操作正在进行时发生故障。操作 正在使用WSAENETRESET失败。后续操作失败 使用WSAECONNRESET


完整源代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using LogManager;

namespace CoreUnitPlatform
{
    public class SocketCommCoreUnit
    {
        #region property
        private volatile bool _shouldStop;
        private LogWriter log = LogWriter.Instance;

        private bool m_bSocketConnected = false;

        private Socket m_clientSocket = null;

        private SocketCommType m_connectedSockType;

        private EventHandlerDataReceived m_evtHandlerDataReceived;

        private EventHandlerSocketConnected m_evtHandlerSocketConnected;

        private EventHandlerSocketConnectedFailed m_evtHandlerSocketConnectedFailed;

        private EventHandlerSocketDisconnected m_evtHandlerSocketDisconnected;

        private IPAddress m_IPAddress;

        private IPEndPoint m_IPEndPoint;

        private int m_portNo;

        private Socket m_serverSocket = null;

        private Thread m_threadConnectSocket = null;

        private string Name = string.Empty;

        #endregion

        #region constructor
        public SocketCommCoreUnit()
        {
            this.Name = "SocketCommCoreUnit";
            Instance();
        }
        #endregion

        #region delegatge
        public delegate void EventHandlerDataReceived(string msg);

        public delegate void EventHandlerSocketConnected();

        public delegate void EventHandlerSocketConnectedFailed();

        public delegate void EventHandlerSocketDisconnected();
        public enum SocketCommType { SERVER, CLIENT };

        public bool SocketConnected
        {
            get { lock (this) { return m_bSocketConnected; } }
            set { lock (this) { m_bSocketConnected = value; } }
        }
        #endregion

        #region public
        public void ConnectSocketProc()
        {
            while (!_shouldStop)
            {
                try
                {
                    if (SocketConnected == false)
                    {
                        if (m_connectedSockType == SocketCommType.SERVER)
                        {
                            m_clientSocket = m_serverSocket.Accept();   // If a client is connected, wait for data from client

                            m_evtHandlerSocketConnected();
                            SocketConnected = true;
                        }
                        else
                        {
                            m_clientSocket.Connect(m_IPAddress, m_portNo);
                            if (m_clientSocket.Connected == true)
                            {
                                m_evtHandlerSocketConnected();
                                SocketConnected = true;
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            byte[] buffer = new byte[1024];
                            int readBytes = this.m_clientSocket.Receive(buffer);
                            if (readBytes == 0)
                            {
                                this.reConnect();
                            }
                            else
                            {
                                string received = System.Text.Encoding.ASCII.GetString(buffer);
                                m_evtHandlerDataReceived(received);
                            }
                        }
                        catch (SocketException sex)
                        {
                            if (sex.NativeErrorCode.Equals(10054))
                            {
                                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured [{0}]: MESASGE[{1}]\r\nSOURCE[{2}]\r\nTRACE[{3}]", sex.NativeErrorCode, sex.Message, sex.Source, sex.StackTrace));

                                this.reConnect();
                            }
                        }
                    }
                }
                catch
                {
                    m_evtHandlerSocketConnectedFailed();
                }

                Thread.Sleep(100);
            }
        }

        public void Initialize(string IP, int port, SocketCommType sockType, EventHandlerDataReceived evtHandlerDataReceived, EventHandlerSocketConnected evtHandlerDataConnected, EventHandlerSocketDisconnected evtHandlerSocketDisconnected, EventHandlerSocketConnectedFailed evtHandlerSocketConnectedFailed)
        {
            m_connectedSockType = sockType;
            m_evtHandlerDataReceived = evtHandlerDataReceived;
            m_evtHandlerSocketDisconnected = evtHandlerSocketDisconnected;
            m_evtHandlerSocketConnected = evtHandlerDataConnected;
            m_evtHandlerSocketConnectedFailed = evtHandlerSocketConnectedFailed;

            m_portNo = port;
            m_IPAddress = IPAddress.Parse(IP);
            m_IPEndPoint = new IPEndPoint(m_IPAddress, m_portNo);

            if (sockType == SocketCommType.SERVER)
            {
                OpenServer();
            }
            else
            {
                OpenClient();
            }
        }

        public void Instance()
        {
        }

        public void OpenClient()
        {
            try
            {
#if _NO_USE_SOCKET
#else
                RunClientSocket();
#endif
            }
            catch (System.Exception ex)
            {
                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
            }
        }

        public void OpenServer()
        {
            try
            {
#if _NO_USE_SOCKET
#else
                RunServerSocket();
#endif
            }
            catch (System.Exception ex)
            {
                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
            }
        }

        public void Release()
        {
            try
            {
                if (this.m_clientSocket != null && this.m_clientSocket.Connected)
                {
                    SocketConnected = false;
                    m_evtHandlerSocketDisconnected();

                    this.m_clientSocket.Shutdown(SocketShutdown.Both);
                    this.m_clientSocket.Close();
                }

                if (m_serverSocket != null)
                {
                    m_serverSocket.Close();
                }

                if ((m_threadConnectSocket != null) && (m_threadConnectSocket.IsAlive == true))
                {
                    Thread.Sleep(1);
                    RequestStop();

                    SocketConnected = false;
                    m_threadConnectSocket.Abort();
                    m_threadConnectSocket.Join();
                }
            }
            catch (System.Exception ex)
            {
                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
            }
        }

        public void RequestStop()
        {
            _shouldStop = true;
        }

        public void RunClientSocket()
        {
            m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ConfigureTcpSocket(m_clientSocket, SocketCommType.CLIENT);

            m_threadConnectSocket = new Thread(new ThreadStart(ConnectSocketProc));
            m_threadConnectSocket.Start();
        }

        public void RunServerSocket()
        {
            m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_serverSocket.Bind(m_IPEndPoint);
            m_serverSocket.Blocking = true;          // The server socket is working in blocking mode

            ConfigureTcpSocket(m_serverSocket, SocketCommType.SERVER);

            m_serverSocket.Listen(1);

            m_threadConnectSocket = new Thread(new ThreadStart(ConnectSocketProc));
            m_threadConnectSocket.Start();
        }

        public void Send(byte[] msg)
        {
#if _NO_USE_SOCKET
#else
            if (SocketConnected == false)
            {
                throw new Exception("SOCKET_NOT_CONNECT_BEFORE_SEND_DATA;");
            }

            try
            {
                m_clientSocket.Send(msg);
            }
            catch (System.Exception ex)
            {
                SocketConnected = false;
                m_evtHandlerSocketDisconnected();
                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
            }
#endif
        }

        #endregion

        #region private

        private void ConfigureTcpSocket(Socket tcpSocket, SocketCommType socketCommType)
        {
            //// Don't allow another socket to bind to this port.
            //tcpSocket.ExclusiveAddressUse = true;

            //// The socket will linger for 10 seconds after
            //// Socket.Close is called.
            //tcpSocket.LingerState = new LingerOption(true, 10);

            // Disable the Nagle Algorithm for this tcp socket.
            tcpSocket.NoDelay = true;

            //if (socketCommType == SocketCommType.CLIENT)
            //{
            //    tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);
            //    tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //    //tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
            //    //tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000);

            //    // Set the receive buffer size to 8k
            //    tcpSocket.ReceiveBufferSize = 2048;

            //    // Set the send buffer size to 8k.
            //    tcpSocket.SendBufferSize = 2048;
            //}

            //// Set the receive buffer size to 8k
            //tcpSocket.ReceiveBufferSize = 1024;

            // Set the timeout for synchronous receive methods to
            // 1 second (1000 milliseconds.)
            //tcpSocket.ReceiveTimeout = 1000;

            //// Set the send buffer size to 8k.
            //tcpSocket.SendBufferSize = 1024;

            // Set the timeout for synchronous send methods
            // to 1 second (1000 milliseconds.)
            //tcpSocket.SendTimeout = 1000;

            //// Set the Time To Live (TTL) to 42 router hops.
            //tcpSocket.Ttl = 42;
        }

        private void ConfigureTcpSocket(Socket tcpSocket)
        {
            //// Don't allow another socket to bind to this port.
            //tcpSocket.ExclusiveAddressUse = true;

            //// The socket will linger for 10 seconds after
            //// Socket.Close is called.
            //tcpSocket.LingerState = new LingerOption(true, 10);

            // Disable the Nagle Algorithm for this tcp socket.
            tcpSocket.NoDelay = true;

            //// Set the receive buffer size to 8k
            //tcpSocket.ReceiveBufferSize = 8192;

            // Set the timeout for synchronous receive methods to
            // 1 second (1000 milliseconds.)
            //tcpSocket.ReceiveTimeout = 1000;

            //// Set the send buffer size to 8k.
            //tcpSocket.SendBufferSize = 8192;

            // Set the timeout for synchronous send methods
            // to 1 second (1000 milliseconds.)
            //tcpSocket.SendTimeout = 1000;

            //// Set the Time To Live (TTL) to 42 router hops.
            //tcpSocket.Ttl = 42;
        }

        private void reConnect()
        {
            try
            {
                SocketConnected = false;
                m_evtHandlerSocketDisconnected();
                m_clientSocket.Disconnect(true);

                log.AddSystemLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Try Re-Connection..."));

                if (m_connectedSockType == SocketCommType.SERVER)
                {
                }
                else
                {
                    m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
            }
            catch (System.Exception exc)
            {
                log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", exc.Message, exc.Source, exc.StackTrace));
            }
        }
        #endregion
    }
}
我在这里发表了一篇关于异步套接字的(IMOHO)文章,其中有一些关于服务器/客户端套接字的伪代码

第条:


我认为异步示例的代码很棒。

我建议您看看异步变体。开始接收/结束接收。为了重新连接,最好为它创建一个新的套接字。@JeroenvanLangen reConnect()方法已经创建了一个新套接字。不是吗?告诉我更多细节。这会有帮助的。我看到它被重新创建了。为什么服务器代码和客户机代码结合在一起?在这种情况下,“控制器”是什么?@JeroenvanLangen我希望将代码重新用于其他应用程序的原因。有时我需要同时连接服务器和客户端控制器。“控制器”是具有TCP/IP芯片组的第三方设备。它是服务器。我的电脑已连接到许多服务器,这些服务器是第三方设备。快50了。我决定使用线程来轮询,而不是像回调这样的事件方法。您认为我必须更改回调方法吗?我认为对许多客户机使用异步方法更好。您不希望为每个连接生成一个线程。异步套接字将使用IOCP,有关IOCP的详细信息,请参见:…这样它就不会挂在线程池线程上。您的博客无法正常工作。你为什么不在这里发布一些信息呢?