예제 #1
0
        /// <summary>
        /// Updates the state of the server and waits for a command to become available.
        /// The first command that is available will be passed into a handler.
        /// </summary>
        /// <param name="handler">The <see cref="IPokeCommandHandler"/> to handle the command with.</param>
        public bool ReceiveCommand(IPokeCommandHandler handler)
        {
            // Duplicate our clients list for use with Socket.Select()
            List <Socket> readyClients;
            List <Socket> failedClients = new List <Socket>();

            lock (_clients)
            {
                readyClients = new List <Socket>(_clients);
            }

            // The listener socket is "readable" when a client is ready to be accepted
            readyClients.Add(_listener);

            // Wait for either a command to become available in a client,
            // or a client to be ready to connect
            Socket.Select(readyClients, null, null, -1);
            foreach (var socket in readyClients)
            {
                if (socket != _listener)
                {
                    try
                    {
                        // Command available
                        using (var stream = new NetworkStream(socket, false))
                        {
                            var command = CommandSerialization.DeserializeCommand(stream);
                            if (command != null)
                            {
                                SendCommandToAll(command);
                                command.Handle(handler);
                            }
                        }
                    }
                    catch (IOException)
                    {
                        failedClients.Add(socket);
                    }
                    break;                     // Only process one command at a time
                }
                else
                {
                    // Client ready to connect
                    var client = _listener.Accept();
                    ConnectClient(client);
                }
            }

            foreach (var socket in failedClients)
            {
                RemoveClient(socket);
                _clients.Remove(socket);
                socket.Close();
            }
            return(true);
        }
예제 #2
0
 public void ReceiveCommand(IPokeCommandHandler handler)
 {
     using (var stream = new NetworkStream(_socket, false))
     {
         var command = CommandSerialization.DeserializeCommand(stream);
         if (command != null)
         {
             command.Handle(handler);
         }
         else
         {
             Close();
         }
     }
 }