public void SendAll <T>(byte system, byte type, T data) { var json = Serialize(system, type, data); foreach (var connection in _socketRepository.GetAllConnections()) { var stream = connection?.Stream; if (stream != null) { _webSocketCore.Send(stream, json); } } }
public void HandleDeadPlayers() { var connections = _socketRepository.GetAllConnections(); var timeouts = connections.Where(x => x.TcpClient == null || x.IsTimedOut()).ToList(); foreach (var timeout in timeouts) { Player player = null; var playerId = _socketRepository.GetPlayerId(timeout.Id); if (playerId.HasValue) { player = _playerRepository.GetPlayerById(playerId.Value); } Console.WriteLine($"Connection removed: {timeout.Id} - {timeout.LastMessage}"); _socketRepository.RemoveConnection(timeout.Id); if (player != null) { _locationSender.Update(player.Node); } } }
public List <WebSocketMessage> PollMessages() { var output = new List <WebSocketMessage>(); var sockets = _socketRepository.GetAllConnections(); for (var i = 0; i < sockets.Count; i++) { var socket = sockets[i]; var data = new List <byte>(); while (socket.TcpClient.Client.Poll(10, SelectMode.SelectRead)) { var buffer = new byte[1024]; var received = socket.Stream.Read(buffer, 0, buffer.Length); if (received == 0) { break; } data.AddRange(buffer.Take(received)); } if (socket.IsTimedOut()) { Console.WriteLine("Dead connection (" + socket.Id + ")"); sockets.RemoveAt(i); i--; continue; } if (!data.Any()) { continue; } if (data[0] != BinaryFrame) { continue; } ulong size = 0; var payloadIndex = 0; var mask = new byte[4]; if (data[1] <= 253) { size = (data[1]); mask = data.Skip(2).Take(4).ToArray(); payloadIndex = 6; } else if (data[1] == 254) { size = BitConverter.ToUInt16(data.ToArray(), 1); mask = data.Skip(4).Take(4).ToArray(); payloadIndex = 8; } else if (data[1] == 255) { size = BitConverter.ToUInt64(data.ToArray(), 1); mask = data.Skip(10).Take(4).ToArray(); payloadIndex = 14; } var payload = data.Skip(payloadIndex).Take((int)size).ToArray(); for (var j = 0; j < payload.Length; j++) { payload[j] = (byte)(payload[j] ^ mask[j % 4]); } if (payload[0] == SystemTypes.Ping) { socket.LastMessage = DateTime.Now; continue; } var jsonData = Encoding.UTF8.GetString(payload, 2, payload.Count() - 2); Console.WriteLine(jsonData); WebSocketMessage message = new WebSocketMessage { System = payload[0], Type = payload[1], Data = jsonData }; if (message.HasData()) { message.Connection = socket; output.Add(message); } } return(output); }