public void SendEnvironmentState(Commands.EnvironmentState state) { Clients.ForEach(c => { Packets.Send(c.Peer, state, DeliveryMethod.ReliableSequenced); }); }
public void OnInfoCommand(Commands.Info info, NetPeer peer) { Debug.Assert(MasterState == State.Connecting); var client = Clients.Find(c => c.Peer == peer); Debug.Assert(client != null); Debug.Assert(client.State == State.Connecting); Debug.Log($"NET: Client connected from {peer.EndPoint}"); Debug.Log($"NET: Client version = {info.Version}"); Debug.Log($"NET: Client Unity version = {info.UnityVersion}"); Debug.Log($"NET: Client OS = {info.OperatingSystem}"); client.State = State.Connected; var sim = Loader.Instance.SimConfig; if (!sim.ApiOnly) { if (Clients.All(c => c.State == State.Connected)) { var load = new Commands.Load() { Name = sim.Name, MapName = sim.MapName, MapUrl = sim.MapUrl, ApiOnly = sim.ApiOnly, Headless = sim.Headless, Interactive = sim.Interactive, TimeOfDay = sim.TimeOfDay.ToString("o", CultureInfo.InvariantCulture), Rain = sim.Rain, Fog = sim.Fog, Wetness = sim.Wetness, Cloudiness = sim.Cloudiness, Agents = Simulation.Agents.Select(a => new Commands.LoadAgent() { Name = a.Name, Url = a.Url, Bridge = a.Bridge == null ? string.Empty : a.Bridge.Name, Connection = a.Connection, Sensors = a.Sensors, }).ToArray(), UseTraffic = Simulation.UseTraffic, UsePedestrians = Simulation.UsePedestrians, }; foreach (var c in Clients) { Packets.Send(c.Peer, load, DeliveryMethod.ReliableOrdered); c.State = State.Loading; } MasterState = State.Loading; } } }
public void Send(Packets.GameInput gameInput) { server.MatchSome(server => { packetProcessor.Send <Packets.GameInput>( server, gameInput, DeliveryMethod.ReliableOrdered ); }); }
void Start() { //Listener es el encargado de gestionar todos los paquetes recibidos netListenerServer = new EventBasedNetListener(); //Packet processor es el encargado de procesar los paquetes creados por nosotros, pudiendo leerlos y enviarlos netManagerServer = new NetManager(netListenerServer); //Manager es donde tenemos todos los datos de la conexion, como el peer netPacketProcessorServer = new NetPacketProcessor(); //netManagerServer.NatPunchEnabled = true; netManagerServer.Start(port); //Evento recibido al recibir un intento de conexion netListenerServer.ConnectionRequestEvent += (request) => { if (netManagerServer.ConnectedPeersCount < maxConnections) { request.AcceptIfKey(connectionKey); } else { request.Reject(); } }; //Evento estandar, cualquiera que no es especial como conectarse, desconectarse o ping netListenerServer.NetworkReceiveEvent += (peer, reader, deliveryMethod) => { //Lee los paquetes recibidos y llama a los listeners de cada paquete de los que haya recibido netPacketProcessorServer.ReadAllPackets(reader, peer); }; //Aqui estaran todos los listeners necesarios para cada paquete RegisterPacketsListeners(); //Evento lanzado al tener un nuevo cliente conectado netListenerServer.PeerConnectedEvent += (client) => { Debug.Log("Client connected: " + client); netPacketProcessorServer.Send(client, new WelcomePacket() { NumberValue = 1, StringValue = "Hola" }, DeliveryMethod.ReliableOrdered); netPacketProcessorServer.Send(client, new PositionPacktet() { position = new Vector3(5, 6, 7) }, DeliveryMethod.ReliableOrdered); }; }
public void SendDecreaseHp(int decreaseQuantity) { netPacketProcessorClient.Send(netManagerClient.FirstPeer, new HpPlayerDecreasedPacket() { DecreasedQuantity = decreaseQuantity }, DeliveryMethod.ReliableOrdered); }
public void Run() { //setup netpacketprocessor _netPacketProcessor.RegisterNestedType <CustomStruct>(); _netPacketProcessor.SubscribeReusable <ArgumentsForLogin, NetPeer>(Method1); //setup events EventBasedNetListener clientListener = new EventBasedNetListener(); EventBasedNetListener serverListener = new EventBasedNetListener(); serverListener.ConnectionRequestEvent += request => { request.AcceptIfKey("key"); }; serverListener.NetworkReceiveEvent += (peer, reader, channel, method) => { _netPacketProcessor.ReadAllPackets(reader, peer); }; clientListener.PeerConnectedEvent += peer => { //send after connect var testList = new List <CustomStruct> { new CustomStruct { X = 1, Y = -1 }, new CustomStruct { X = 5, Y = -28 }, new CustomStruct { X = -114, Y = 65535 } }; _netPacketProcessor.Send( peer, new ArgumentsForLogin { Password = "******", SomeInt = 5, UserId = "someUser", SomeList = testList }, DeliveryMethod.ReliableOrdered); }; //start client/server _client = new NetManager(clientListener); _server = new NetManager(serverListener); _client.Start(); _server.Start(9050); _client.Connect("localhost", 9050, "key"); while (!Console.KeyAvailable) { _server.PollEvents(); _client.PollEvents(); Thread.Sleep(10); } _client.Stop(); _server.Stop(); }
public void SendClientActions(PlayerActions actions) { UpdatePacket up = new UpdatePacket() { PlayerAction = (int)actions }; _packetProcessor.Send <UpdatePacket>(_server, up, DeliveryMethod.ReliableOrdered); }
private void SendToAllExceptSender <T>(T packet, NetPeer peer, DeliveryMethod deliveryMethod) where T : class, new() { foreach (NetPeer sendPeer in netManagerServer.ConnectedPeerList) { if (sendPeer.Id == peer.Id) { netPacketProcessorServer.Send(sendPeer, packet, deliveryMethod); } } }
internal bool VoicePlugin_ConnectionEstablished(Connection e) { try { if (_connectionInfo == null) { VoicePlugin.Log("ConnectionEstablished no info ({0})", e.GUID); return(false); } if (!e.IsInitialized) { VoicePlugin.Log("ConnectionEstablished not initialized ({0})", e.GUID); return(false); } if (e.GUID == _connectionInfo.ServerGUID) { if (e.IsVoiceEnabled) { VoicePlugin.Log("ConnectionEstablished Gotcha! ({0})", e.GUID); } e.UpdateSetup(_connectionInfo); _netPacketProcessor.Send(Client, new VoicePaketConnectClient() { ClientGUID = _configuration.ClientGUID, TeamspeakID = e.LocalClient.GUID, TeamspeakClientID = e.LocalClientId, TeamspeakClientName = e.LocalClient.Name, MicrophoneMuted = e.LocalClient.IsMicrophoneMuted, SpeakersMuted = e.LocalClient.IsSpeakersMuted }, DeliveryMethod.ReliableOrdered); } else { VoicePlugin.Log("ConnectionEstablished wrong server ({0})", e.GUID); } return(true); } catch (Exception ex) { VoicePlugin.Log(ex.ToString()); return(false); } }
public void SendToAllClients <T>(T packet, DeliveryMethod method = DeliveryMethod.ReliableOrdered) where T : class, new() { DebugUtils.Assert(connectedClients.Count > 0, "No connected clients to send packet to!"); foreach (var clientID in connectedClients.Keys) { processor.Send(connectedClients[clientID], packet, method); } }
private Thread GetConnectionThread() { return(new Thread(() => { while (!connected) { try { server = client.Connect(hostname, port, "patricio"); Debug.WriteLine("Attempting to Connect"); var packet = new Packet { PacketType = PacketType.LOGIN, Username = username }; processor.Send(server, packet, DeliveryMethod.ReliableOrdered); } catch { } Thread.Sleep(5000); } })); }
public void Run() { //setup netpacketprocessor _netPacketProcessor.SubscribeReusable <ArgumentsForLogin, NetPeer>(Method1); //setup events EventBasedNetListener clientListener = new EventBasedNetListener(); EventBasedNetListener serverListener = new EventBasedNetListener(); serverListener.ConnectionRequestEvent += request => { var key = System.Text.Encoding.UTF8.GetBytes("key"); if (request.Data.SequenceEqual(key)) { request.Accept(); } }; serverListener.NetworkReceiveEvent += (peer, reader, method) => _netPacketProcessor.ReadAllPackets(reader, peer); //start client/server _client = new NetManager(clientListener); _server = new NetManager(serverListener); _client.Start(); _server.Start(9050); var clientPeer = _client.Connect("localhost", 9050, "key"); //send _netPacketProcessor.Send( clientPeer, new ArgumentsForLogin { Password = "******", SomeInt = 5, UserId = "someUser" }, DeliveryMethod.ReliableOrdered); while (!Console.KeyAvailable) { _server.PollEvents(); Thread.Sleep(10); } _client.Stop(); _server.Stop(); }
public void OnPeerConnected(NetPeer peer) { Debug.Assert(ClientState == State.Initial); Master = peer; Debug.Log($"Master {peer.EndPoint} connected"); var info = new Commands.Info() { Version = "todo", UnityVersion = Application.unityVersion, OperatingSystem = SystemInfo.operatingSystemFamily.ToString(), }; Packets.Send(Master, info, DeliveryMethod.ReliableOrdered); ClientState = State.Connected; }
public void ProcessPacket(pl sp, NetPeer p) { sp.Tickets--; Console.WriteLine($"{ServerSignature} Received Packet! Details: {sp.Name} with {sp.Tickets}"); _netPacketProcessor.Send(p, sp, DeliveryMethod.ReliableOrdered); }
public void Start() { Console.WriteLine("GAME SERVER STARTED"); EventBasedNetListener listener = new EventBasedNetListener(); NetManager server = new NetManager(listener); server.Start(9050 /* port */); _netSerializer.Register <WelcomePacket>(); _netSerializer.Register <UpdatePacket>(); _netSerializer.Register <ServerSnapshotPacket>(); _netSerializer.Register <EchoPacket>(); _packetProcessor.SubscribeReusable <UpdatePacket, NetPeer>(HandleClientUpdate); listener.ConnectionRequestEvent += request => { //we will change this when we create 'game sessions' for now we only support the 4 players. if (server.PeersCount < 4 /* max connections */) { request.AcceptIfKey("SomeConnectionKey"); } else { request.Reject(); } }; listener.PeerConnectedEvent += peer => { //server stores by ipaddress+port string key = peer.EndPoint.ToString(); if (!_knownPlayers.ContainsKey(key)) { // new unknown player connected, let's start tracking them ServerPlayerData pd = new ServerPlayerData { //generate a unique ID for the peer connecting which will be referenced in the future (by other peers as an intermediary (vs telling peers specifically who they're connected to IP/POrt or whatever) // let's condense this down by 1/3 or so.. (also we know the final characters are == ClientID = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Replace("=", ""), GameSessionId = string.Empty, IPAddress = peer.EndPoint.Address, Port = peer.EndPoint.Port, MillisecondsSinceLastHeard = 0, PlayerNumber = GetNextPlayerId() + 1, PlayerLocation = new Loc { X = 0, Y = 0 }, _clientRef = peer }; bool success = _knownPlayers.TryAdd(key, pd); pd.PlayerLocation.X = pd.PlayerNumber * 15; pd.PlayerLocation.Y = pd.PlayerNumber * 15; } else { //player must have disconnected during a game, let's try to reconnect to their game if it's still playing //TODO: look up the GameSessionID, then start sending this player's packets to all players in the session } var pdat = _knownPlayers[key]; Console.WriteLine("PLAYER JOINED: {0} as PLAYER {1} with ID {2}", peer.EndPoint, pdat.PlayerNumber, pdat.ClientID); //send our info in a welcome packet WelcomePacket wp = new WelcomePacket { PlayerId = pdat.ClientID, PlayerNumber = pdat.PlayerNumber, XStart = pdat.PlayerLocation.X, YStart = pdat.PlayerLocation.Y }; _packetProcessor.Send <WelcomePacket>(peer, wp, DeliveryMethod.ReliableOrdered); Console.WriteLine("Packet Processor Sent Packet!"); //peer.Send(_netSerializer.Serialize<WelcomePacket>(wp), DeliveryMethod.ReliableOrdered); }; listener.NetworkReceiveEvent += Listener_NetworkReceiveEvent; while (!Console.KeyAvailable) { server.PollEvents(); UpdateAllClients(); //sends a snapshot of all client locations every 15ms Thread.Sleep(15); } server.Stop(); }
public void SendCommand <T>(NetPeer peer, T command) where T : class, new() { var deliveryMethod = NetCommand.Metadata.DeliveryType[typeof(T)]; netPacketProcessor.Send(peer, command, deliveryMethod); }
public void SendPacket(pl thePl) { _netPacketProcessor.Send <pl>(Server, thePl, DeliveryMethod.ReliableOrdered); }
public void SendPacket <T>(T packet) where T : class, new() { processor.Send(peer, packet, DeliveryMethod.ReliableOrdered); }