Exemplo n.º 1
0
        private static void HandleClients(object obj)
        {
            try
            {
                int       clientID = (int)obj;
                TcpClient client;
                lock (_lock)
                {
                    client = clientTable[clientID];
                }

                while (true)
                {
                    try
                    {
                        NetworkStream stream          = client.GetStream();
                        byte[]        buffer          = new byte[1024];
                        int           bufferNoOfBytes = stream.Read(buffer, 0, buffer.Length);
                        if (bufferNoOfBytes == 0)
                        {
                            break;
                        }

                        string data = Encoding.ASCII.GetString(buffer, 0, bufferNoOfBytes);
                        Broadcast(data);
                        LogServer.Message(data);
                        Console.WriteLine(data);
                    }
                    catch (Exception ex)
                    {
                        LogServer.Error(ex);
                    }
                }

                lock (_lock)
                {
                    clientTable.Remove(clientID);
                }

                client.Client.Shutdown(SocketShutdown.Both);
                LogServer.Message("Client disconnected...");
                Console.WriteLine("Client disconnected...");
                client.Close();
            }
            catch (Exception ex)
            {
                LogServer.Error(ex);
            }
        }
Exemplo n.º 2
0
        public static void Main()
        {
            int clientCount = 1;
            var port        = 8888;

            TcpListener serverSocket = new TcpListener(IPAddress.Any, port);

            serverSocket.Start();

            Thread serverListeningMessageOnDisplayThread = new Thread(ServerListeningMessageOnDisplay);

            serverListeningMessageOnDisplayThread.Start();

            while (true)
            {
                try
                {
                    TcpClient client = serverSocket.AcceptTcpClient();
                    lock (_lock)
                    {
                        clientTable.Add(clientCount, client);
                    }

                    LogServer.Message("Client connected!");
                    Console.WriteLine("Client connected!");

                    Thread clientThread = new Thread(HandleClients);
                    clientThread.Start(clientCount);
                    clientCount++;
                }
                catch (Exception ex)
                {
                    LogServer.Error(ex);
                }
            }
        }