Пример #1
0
        private void HandleClientComm(object client)
        {
            TcpClientAdapter tcpClient = (TcpClientAdapter)client;

            clients.Add(tcpClient);

            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int    bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();

                if (MessageReceived != null)
                {
                    MessageReceived(this, new NetworkMessageEvent(encoder.GetString(message, 0, bytesRead)));
                }
            }

            tcpClient.Close();
        }
Пример #2
0
        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true)
            {
                //blocks until a client has connected to the server
                TcpClientAdapter client = new TcpClientAdapter(this.tcpListener.AcceptTcpClient());

                if (ClientConnect != null)
                {
                    ClientConnect(this, new ClientConnectEvent(client));
                }


                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }