Exemple #1
0
            private void ClientHandler <M>(Socket clientSocket)
            {
                clientList.Add(clientSocket);
                OnServerAccept?.Invoke(this, new AcceptEventArgs(clientSocket));
                int    fullMessageSize;
                string fullMessage;

                byte[] messageBuffer = new byte[1024];
                while (true)
                {
                    fullMessage     = string.Empty;
                    fullMessageSize = 0;
                    try
                    {
                        do
                        {
                            int messageSize = clientSocket.Receive(messageBuffer);
                            fullMessageSize += messageSize;
                            fullMessage     += Encoding.UTF8.GetString(messageBuffer, 0, messageSize);
                        } while (clientSocket.Available > 0);
                        OnServerReceive?.Invoke(this, new EventArgs());
                    }
                    catch (Exception exception)
                    {
                        OnReceiveException?.Invoke(this, new ExceptionEventArgs(clientSocket, exception));
                        break;
                    }

                    List <ByteArray> byteArrays = Buffer.SplitBuffer(Encoding.UTF8.GetBytes(fullMessage), 0);

                    object message = default;
                    foreach (var byteArray in byteArrays)
                    {
                        if (typeof(M) != typeof(string))
                        {
                            message = JsonSerializer.Deserialize <M>(Encoding.UTF8.GetString(byteArray.bytes));
                        }
                        else
                        {
                            message = Encoding.UTF8.GetString(byteArray.bytes);
                        }
                        MessageProcessing?.Invoke(this, new MessageProcessEventArgs(new MessageData(message, fullMessageSize, fullMessage)));
                    }
                }
            }
Exemple #2
0
 /* Relay exceptions to event. */
 private void ReceiveException(ref NetMessage <GenericExceptionResponse> message)
 {
     OnReceiveException?.Invoke(message.Message);
 }