Esempio n. 1
0
 public void StartReceive()
 {
     if (!_isReceiveStart)
     {
         _isReceiveStart = true;
         ReadStateObject state = new ReadStateObject();
         state.workSocket = _socket;
         state.Source     = this;
         _socket.BeginReceive(state.buffer, 0, ReadStateObject.BufferSize, SocketFlags.None,
                              new AsyncCallback(ReadCallback), state);
     }
 }
Esempio n. 2
0
        public static void ReadCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            ReadStateObject state   = (ReadStateObject)ar.AsyncState;
            Socket          handler = state.workSocket;

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

                // handle FIN
                if (bytesRead == 0)
                {
                    state.Source.Shutdown();
                    return;
                }

                if (bytesRead > 0)
                {
                    // raise event
                    state.Source.SocketReceiveEvent?.Invoke(state.Source, new SocketReceiveEventArgs(state.buffer.Take(bytesRead).ToArray()));
                }

                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, ReadStateObject.BufferSize, SocketFlags.None,
                                     new AsyncCallback(ReadCallback), state);
            }
            catch (SocketException ex)
            {
                // disconnection detected
                switch ((SocketError)ex.ErrorCode)
                {
                case SocketError.ConnectionReset:
                    state.Source.Shutdown();
                    break;

                default:
                    state.Source.Shutdown();
                    break;
                }
            }
            catch (ObjectDisposedException) { }  // the socket has been disposed.
        }