/// <summary> /// Sends a command to all connected clients. /// </summary> /// <param name="command">The command to send.</param> public void SendCommandToAll(PokeCommand command) { IList <Socket> failedClients = new List <Socket>(); lock (_clients) { foreach (var socket in _clients) { try { using (var netStream = new NetworkStream(socket, false)) { using (var bufStream = new BufferedStream(netStream)) { CommandSerialization.SerializeCommand(command, bufStream); } } } catch (IOException) { failedClients.Add(socket); } } foreach (var socket in failedClients) { _clients.Remove(socket); socket.Close(); } } }
/// <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); }
public void SendCommand(PokeCommand command) { using (var netStream = new NetworkStream(_socket, false)) { using (var bufStream = new BufferedStream(netStream)) { CommandSerialization.SerializeCommand(command, bufStream); } } }
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(); } } }