Exemple #1
0
        public void Listen()
        {
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);

            listener = new TcpListener(localAdd, PORT);
            Console.WriteLine("Listening...");
            listener.Start();

            while (true)
            {
                TcpClient tcpClient = listener.AcceptTcpClient();

                // var client = new Client(tcpClient);

                NetworkStream nwStream = tcpClient.GetStream();
                object        received = JsonSerializerProvider.DeserializeBinary(nwStream);

                if (received is Account account)
                {
                    Console.WriteLine("A new client connected");
                    Console.WriteLine("Received: {0}#{1}", account.Username, account.PublicId);
                    //connectedClients.RemoveAll(x => x.tcpClient == client.tcpClient);
                    account.tcpClient = tcpClient;
                    AddConnection(account);
                    new Thread(() => ListenToClient(account)).Start();
                }
            }
        }
Exemple #2
0
        private void InterpretIncomingMessage(NetworkStream nwStream)
        {
            object received = JsonSerializerProvider.DeserializeBinary(nwStream);

            if (received is Message message)
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
                Console.WriteLine("Message from {0} to {1}, {2}: {3}", message.SenderUniqueId, message.ReceiverUniqueId, message.Timestamp,
                                  System.Text.Encoding.UTF8.GetString(message.EncryptedMessage));
                try
                {
                    var receiver = connectedAccounts.FirstOrDefault(x => x.Id == message.ReceiverUniqueId);
                    if (receiver != null)
                    {
                        var receiverNwStream = receiver.tcpClient.GetStream();
                        // Writes serialized binary data into the stream
                        JsonSerializerProvider.SerializeBinary(receiverNwStream, message);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                }
            }
            else if (received is FriendRequest request)
            {
                HandleFriendRequest(request);
            }
            else if (received is FriendResponse response)
            {
                HandleFriendResponse(response);
            }
            else
            {
                Console.WriteLine("Received: " + received);
            }
        }