コード例 #1
0
        private void HandleClientCommunication(object client)
        {
            try
            {
                if (!(client is TcpUser user))
                {
                    throw new InstanceNotFoundException("TcpUser was not found");
                }

                var clientStream = user.ClientStream;

                var message = new byte[32768];

                while (true)
                {
                    int bytesRead;

                    try
                    {
                        //// blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 32768);
                    }
                    catch (IOException ex)
                    {
                        ex.Handle(ExceptionHandlingOptions.RecordOnly, Log);
                        break;
                    }
                    catch (ObjectDisposedException ex)
                    {
                        ex.Handle(ExceptionHandlingOptions.RecordOnly, Log);
                        break;
                    }

                    if (bytesRead == 0)
                    {
                        //// the client has disconnected from the server
                        Log.InfoFormat("Client[{0}, {1}] disconnected.", user.Id, user.IpAddress);
                        break;
                    }

                    //// message has successfully been received
                    var encoder = new ASCIIEncoding();
                    OnNetworkMessageReceived?.Invoke(user, new NetworkEventArgs {
                        Message = encoder.GetString(message, 0, bytesRead)
                    });
                }

                OnTcpUserStatusChanged?.Invoke(user, new NetworkEventArgs {
                    SocketStatus = TcpSocketStatus.Disconnected
                });

                //// lost the user
                Repository.Delete(user.Id);
                Log.InfoFormat("Connection Lost from {0}", user.IpAddress);
            }
            catch (InstanceNotFoundException ex)
            {
                ex.Handle(ExceptionHandlingOptions.RecordAndThrow, Log);
            }
        }
コード例 #2
0
        /// <summary>
        /// Main message received loop
        /// </summary>
        private void MessageRetrieveCallback(IAsyncResult AsyncResult)
        {
            if (Stopping)
            {
                return;
            }

            bool StatusOK;

            try
            {
                if (UseSSL)
                {
                    StatusOK = SSLStream.EndRead(AsyncResult) != 0;
                }
                else
                {
                    StatusOK = BaseSocket.EndReceive(AsyncResult, out var ErrorCode) != 0 && ErrorCode == SocketError.Success;
                }
            }
            catch
            {
                StatusOK = false;
            }

            // Check the message state to see if we've been disconnected
            if (!StatusOK)
            {
                OnNetworkClientDisconnected?.Start(this, new OnNetworkClientDisconnectedEventArgs(BaseSocket?.RemoteEndPoint));
                this.Close();
                return;
            }

            // Take our initial first 4 bytes we've received so we know how large the actual message is
            var BufferLength = BitConverter.ToInt32(NextBufferLength, 0);

            NextBufferLength = new byte[4];

            var Buffer = new byte[BufferLength];

            var BytesReceived = 0;

            while (BytesReceived < BufferLength)
            {
                var BytesReceiving = this.Receive(Buffer, BytesReceived, BufferLength - BytesReceived, SocketFlags.None, out var ErrorCode);
                if (ErrorCode != SocketError.Success)
                {
                    OnNetworkExceptionOccurred?.Start(this, new OnNetworkExceptionOccurredEventArgs(new Exception($"Invalid ammount of data received from Client! Expected {BufferLength} got {BytesReceived} with exception {ErrorCode}")));
                    BeginAcceptMessages();
                    return;
                }
                else
                {
                    BytesReceived += BytesReceiving;
                }
            }

            // Deserialize the decrypted message into a raw object array
            NetworkEvent DeserializedEvent;

            try
            {
                DeserializedEvent = SerializationProdiver.Deserialize <NetworkEvent>(Buffer);
            }
            catch
            {
                OnNetworkExceptionOccurred?.Start(this, new OnNetworkExceptionOccurredEventArgs(new Exception($"Corrupted data received!")));
                BeginAcceptMessages();
                return;
            }

            // Notify that we've received a network event
            OnNetworkMessageReceived?.Start(this, new OnNetworkMessageReceivedEventArgs(DeserializedEvent));

            // Loop
            if (ContinueSubscribing)
            {
                BeginAcceptMessages();
            }
        }