2016-11-10 7 views
0

私は、.NETコアにクライアント/サーバソケットライブラリを作成する段階にあり、別のプロジェクトで使用するための基本的なモデルです。.NETコアでソケット受信を終了する

クライアントでは、1つはリスン、1つは送信、もう1つは受信したメッセージをコンシューマに返す3つのスレッドがあります。

クライアントを閉じるためにシャットダウン機能を実装しようとしています。送信機能と受信機能は両方とも消費者であるため、ManualResetEventを確認するように指示するのは簡単です。

しかし、受信スレッドを閉じるための唯一の方法は、socket.Shutdown()を実行することです。これは、スレッドがsocket.Recieve()でスタックされているためです。このため、リスンスレッドでSocketExceptionがスローされ、キャッチされ、処理され、きれいに閉じられます。しかし、私の問題はSocketExceptionのNativeErrorCodeがなぜクローズしているのかを判断できないときに発生します。

NativeErrorCode 10004エラーだけで、すべてのSocketExceptionsをキャッチしてエラーを隠したくありません。 NativeErrorCodeはSocketExceptionクラスでアクセス可能ではありませんが、IntelliSenseでこれを見ることはできますか?

private void ListenThread() 
    { 
     //Listens for a recieved packet, first thing reads the 'int' 4 bytes at the start describing length 
     //Then reads in that length and deserialises a message out of it 
     try 
     { 
      byte[] lengthBuffer = new byte[4]; 
      while (socket.Receive(lengthBuffer, 4, SocketFlags.None) == 4) 
      { 
       int msgLength = BitConverter.ToInt32(lengthBuffer, 0); 
       if (msgLength > 0) 
       { 
        byte[] messageBuffer = new byte[msgLength]; 
        socket.Receive(messageBuffer); 
        messageBuffer = Prereturn(messageBuffer); 
        Message msg = DeserialiseMessage(messageBuffer); 
        receivedQueue.Enqueue(msg); 
        receivedEvent.Set(); 
        MessagesRecievedCount += 1; 
       } 
      } 
     } 
     catch (SocketException se) 
     { 
      //Need to detect when it's a good reason, and bad, NativeErrorCode does not exist in se 
      //if(se.NativeErrorCode == 10004) 
      //{ 

      // } 
     } 
    } 

答えて

1

代わりのse.NativeErrorCodeあなたはse.SocketErrorCode(System.Net.Sockets.SocketError)を使用することができ、それがより明確です。

また、私は通常、非同期ソケットを使用します。それらはイベントモデル上に構築されているので、何かがソケットバッファに到着すると、コールバック関数が呼び出されます。

public void ReceiveAsync() 
    { 
     socket.BeginReceive(tempBytes, 0, tempBytes.Length, 0, ReadCallback, this);//immediately returns 
    } 

    private void ReadCallback(IAsyncResult ar)//is called if something is received in the buffer as well as if other side closed connection - in this case countBytesRead will be 0 
    { 
     int countBytesRead = handler.EndReceive(ar); 
     if (countBytesRead > 0) 
     { 
      //read tempBytes buffer 
     } 
    } 
関連する問題