2013-09-05 17 views
1

Eveyone.소켓 오류 10054 : 오류 처리 문제

오류 코드 10054를 해결하는 방법은 무엇입니까? 이 오류에 대해 some description이 있습니다. 다음은 통신용 전체 소스 코드입니다. 내 코드가 괜찮은지 아닌지 알고 싶습니다.

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 
    } 
} 
+0

비동기 변형을 살펴 보시기 바랍니다. BeginReceive/EndReceive. 다시 연결하려면 새 소켓을 만드는 것이 좋습니다. –

+0

@JeroenvanLangen reConnect() 메서드는 이미 새 소켓을 만듭니다. 그렇지 않니? 좀 더 자세하게 말해줘. 도움이 될 것입니다. –

+0

나는 그것이 재현 된 것을 본다. 서버 코드와 클라이언트 코드가 결합 된 이유는 무엇입니까? 이 경우 컨트롤러 란 무엇입니까? –

답변

0

내가 여기 비동기 소켓에 대한 (IMOHO) 좋은 게시물을 만들어, 그것은 서버/클라이언트 소켓에 대한 몇 가지 의사 코드가 있습니다.

기사 : Unable to read data correctly from .Net socket in C#

내가 비동기 예제의 코드는 큰 생각합니다.

+0

PC가 타사 장치 인 여러 서버에 연결되어 있습니다. 거의 50입니다. 콜백 메소드와 같은 이벤트가 아니라 폴링에 쓰레드를 사용하기로 결정했습니다. CallBack 메서드를 변경해야합니까? –

+0

많은 클라이언트에서 Async 메서드를 사용하는 것이 더 좋습니다. 각 연결마다 스레드를 생성하고 싶지는 않습니다. 비동기 소켓은 IOCP를 IOCP에서 더 많이 사용합니다 : http://msdn.microsoft.com/en-us/library/windows/desktop/... 그래서 스레드 풀 스레드에 멈추지 않습니다. –

+0

블로그가 작동하지 않습니다. 왜 여기에도 정보를 게시하지 않으시겠습니까? – lkanab