private void Awake() { DontDestroyOnLoad(gameObject); Random r = new Random(); _cachedServerState = new ServerState(); _cachedShootData = new ShootPacket(); _userName = Environment.MachineName + " " + r.Next(100000); LogicTimer = new LogicTimer(OnLogicUpdate); _writer = new NetDataWriter(); _playerManager = new ClientPlayerManager(this); _shootsPool = new GamePool <ShootEffect>(ShootEffectContructor, 100); _packetProcessor = new NetPacketProcessor(); _packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2()); _packetProcessor.RegisterNestedType <PlayerState>(); _packetProcessor.SubscribeReusable <PlayerJoinedPacket>(OnPlayerJoined); _packetProcessor.SubscribeReusable <JoinAcceptPacket>(OnJoinAccept); _packetProcessor.SubscribeReusable <PlayerLeavedPacket>(OnPlayerLeaved); _netManager = new NetManager(this) { AutoRecycle = true, IPv6Enabled = IPv6Mode.Disabled }; _netManager.Start(); }
internal NatPunchModule(NetSocket socket) { _socket = socket; _netPacketProcessor.SubscribeReusable <NatIntroduceResponsePacket>(OnNatIntroductionResponse); _netPacketProcessor.SubscribeReusable <NatIntroduceRequestPacket, IPEndPoint>(OnNatIntroductionRequest); _netPacketProcessor.SubscribeReusable <NatPunchPacket, IPEndPoint>(OnNatPunch); }
public void Initialize() { networkObjects = GetComponent <NetworkObjects>(); // network handlers natPunchEvent.NatIntroductionSuccess += (point, addrType, token) => { var peer = netManager.Connect(point, ConnectionKey); Debug.Log($"NatIntroductionSuccess. Connecting to peer: {point}, type: {addrType}, connection created: {peer != null}"); }; netEvent.PeerConnectedEvent += peer => { Debug.Log("PeerConnected: " + peer.EndPoint); }; netEvent.ConnectionRequestEvent += request => { request.AcceptIfKey(ConnectionKey); }; netEvent.NetworkReceiveEvent += (peer, reader, deliveryMethod) => { netPacketProcessor.ReadAllPackets(reader, peer); }; netEvent.PeerDisconnectedEvent += (peer, disconnectInfo) => { Debug.Log($"Peer {peer} Disconnected: {disconnectInfo.Reason}"); }; // packet handlers netPacketProcessor.SubscribeReusable <NetworkMessagePacket, NetPeer>((packet, peer) => { messages.SyncFromPacket(packet); }); netPacketProcessor.SubscribeReusable <NetworkObjectDataPacket, NetPeer>((packet, peer) => { data.SyncFromPacket(packet); }); // connect netManager = new NetManager(netEvent) { IPv6Enabled = IPv6Mode.Disabled, NatPunchEnabled = true }; netManager.NatPunchModule.Init(natPunchEvent); netManager.Start(); LoadObjectsInNewScene(0); }
public void RegisterPacketsListeners() { //Registramos el serializador del nuevo tipo creado netPacketProcessorClient.RegisterNestedType(SeralizeVector3.Serialize, SeralizeVector3.Deserialize); //Registramos el serializador creado al implementar INetSerializar netPacketProcessorClient.RegisterNestedType <Cat>(() => new Cat()); //Crea el listener que se activara cuando se reciba un paquete de ese tipo netPacketProcessorClient.SubscribeReusable <WelcomePacket>((packet) => { Debug.Log("Test packet received"); Debug.Log(packet.NumberValue); }); netPacketProcessorClient.SubscribeReusable <HpPlayerChanged>((packet) => { Debug.Log("New hp received"); Debug.Log(packet.NewHp); }); netPacketProcessorClient.SubscribeReusable <PositionPacktet>((packet) => { Debug.Log("New vector3 received"); Debug.Log(packet.position); }); }
private void StartProcessor() { _processor = new NetPacketProcessor(); _processor.SubscribeReusable <LoginResponse, NetPeer>(_broadcaster.Login); _processor.SubscribeReusable <PlayerJoined, NetPeer>(_broadcaster.PlayerJoined); _processor.SubscribeReusable <Move, NetPeer>(_broadcaster.Move); }
public DistributedHost( IWorkQueue workQueue, ushort listenPort, bool isListener = true, int disconnectTimeout = -1, INetLogger logger = null) { Contract.Requires(listenPort != 0); ListenPort = listenPort; this.workQueue = workQueue; this.logger = logger; // determine our IP // hat tip https://stackoverflow.com/questions/6803073/get-local-ip-address IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipv4Address = host .AddressList .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork); SocketAddress = new SerializedSocketAddress(new IPEndPoint(ipv4Address, listenPort).Serialize()); netManager = new NetManager(new Listener(this)) { BroadcastReceiveEnabled = true, UnconnectedMessagesEnabled = true }; if (disconnectTimeout != -1) { netManager.DisconnectTimeout = disconnectTimeout; } netPacketProcessor = new NetPacketProcessor(); RegisterType <SerializedSocketAddress>(); RegisterType <DistributedId>(); netPacketProcessor.SubscribeReusable <AnnounceMessage, IPEndPoint>(OnAnnounceReceived); netPacketProcessor.SubscribeReusable <AnnounceResponseMessage, IPEndPoint>(OnAnnounceResponseReceived); netDataWriter = new NetDataWriter(); bool managerStarted; if (isListener) { managerStarted = netManager.Start(ListenPort); } else { managerStarted = netManager.Start(); } if (!managerStarted) { throw new PeerException("Could not start netManager"); } }
void Awake() { Packets.RegisterNestedType(SerializationHelpers.SerializeLoadAgent, SerializationHelpers.DeserializeLoadAgent); Packets.SubscribeReusable <Commands.Info, NetPeer>(OnInfoCommand); Packets.SubscribeReusable <Commands.LoadResult, NetPeer>(OnLoadResultCommand); Manager = new NetManager(this); Manager.UpdateTime = 1; Manager.Start(); }
private void SetupPacketProcessor() { packetProcessor = new NetPacketProcessor(); packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2()); packetProcessor.RegisterNestedType <PlayerState>(); packetProcessor.SubscribeReusable <JoinPacket, NetPeer>(OnJoinReceived.Handle); packetProcessor.RegisterNestedType <ClientPlayer>(); packetProcessor.SubscribeReusable <PlayerSendUpdatePacket, NetPeer>(OnPlayerUpdate.Handle); packetProcessor.SubscribeReusable <LevelChangePacket, NetPeer>(OnLevelChange.Handle); }
void Awake() { Packets.RegisterNestedType(SerializationHelpers.SerializeLoadAgent, SerializationHelpers.DeserializeLoadAgent); Packets.SubscribeReusable <Commands.Load>(OnLoadCommand); Packets.SubscribeReusable <Commands.Run>(OnRunCommand); Manager = new NetManager(this); Manager.UpdateTime = 1; Manager.Start(Constants.Port); DontDestroyOnLoad(this); }
public static void RegisterPackets(NetPacketProcessor processor) { processor.RegisterNestedType <Input>(); processor.RegisterNestedType(Vector3Serializer.Serialize, Vector3Serializer.Deserialize); processor.RegisterNestedType(QuaternionSerializer.Serialize, QuaternionSerializer.Deserialize); processor.SubscribeReusable <ClientSendPositionPacket>(ClientSendPositionPacket.OnReceive); processor.SubscribeReusable <InitialTickPacket>(InitialTickPacket.OnReceive); processor.SubscribeReusable <ClientInputPacket>(ClientInputPacket.OnReceive); processor.SubscribeReusable <HostAckInputPacket>(HostAckInputPacket.OnReceive); processor.SubscribeReusable <HostGameStateOnTickPacket>(HostGameStateOnTickPacket.OnReceive); }
public virtual IObservable <T> RegisterToPacket <T>() where T : class, new() { if (_callbacks.ContainsKey(typeof(T))) { _callbacks.Remove(typeof(T)); } var observableCallback = new ObservablePacket <T>(); _callbacks.Add(typeof(T), observableCallback); NetPacketProcessor.SubscribeReusable <T>(observableCallback.Action); return(observableCallback.OnPacketReceived); }
public Server() { server = new NetManager(this) { AutoRecycle = true, }; playerManager = new PlayerManager(); PacketProcessor = new NetPacketProcessor(); LiteNetLibUtils.RegisterAllPacketNestedTypes(PacketProcessor); PacketProcessor.SubscribeReusable <Movement, NebulaConnection> (OnPlayerMovement); PacketProcessor.SubscribeReusable <PlayerAnimationUpdate, NebulaConnection> (OnPlayerAnimationUpdate); PacketProcessor.SubscribeReusable <VegeMined, NebulaConnection>(OnVegeMinedUpdate); }
private void SetListeners() { _packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2()); _packetProcessor.RegisterNestedType <PlayerState>(); _packetProcessor.RegisterNestedType <GroundItemPacket>(); _packetProcessor.RegisterNestedType <ServerItemPacket>(); _packetProcessor.RegisterNestedType <NpcSpawnPacket>(); _packetProcessor.RegisterNestedType <DialogueOptionPacket>(); _packetProcessor.SubscribeReusable <LoginValidatedPacket>(OnLoginValidated); _packetProcessor.SubscribeReusable <RemotePlayerLoginPacket>(OnRemotePlayerConnected); _packetProcessor.SubscribeReusable <LoginAcceptPacket>(OnLoginAccepted); _packetProcessor.SubscribeReusable <PlayerDisconnectedPacket>(OnPlayerLeft); _packetProcessor.SubscribeReusable <PlayerInitialDataPacket>(OnReceiveItemData);; }
public void CustomPackageTest() { var writer = new NetDataWriter(); _packetProcessor.Write(writer, _samplePacket); var reader = new NetDataReader(writer.CopyData()); SamplePacket readPackage = null; _packetProcessor.SubscribeReusable <SamplePacket>( packet => { readPackage = packet; }); _packetProcessor.ReadAllPackets(reader); Assert.NotNull(readPackage); Assert.IsTrue(AreSame(_samplePacket.EmptyString, readPackage.EmptyString)); Assert.AreEqual(_samplePacket.SomeFloat, readPackage.SomeFloat); Assert.AreEqual(_samplePacket.SomeIntArray, readPackage.SomeIntArray); Assert.IsTrue(AreSame(_samplePacket.SomeString, readPackage.SomeString)); Assert.AreEqual(_samplePacket.SomeVector2, readPackage.SomeVector2); Assert.AreEqual(_samplePacket.SomeVectors, readPackage.SomeVectors); Assert.AreEqual(_samplePacket.SomeEnum, readPackage.SomeEnum); Assert.AreEqual(_samplePacket.TestObj.Value, readPackage.TestObj.Value); Assert.AreEqual(_samplePacket.TestArray, readPackage.TestArray); Assert.AreEqual(_samplePacket.SomeByteArray, readPackage.SomeByteArray); Assert.AreEqual(_samplePacket.SampleClassArray, readPackage.SampleClassArray); }
public void Start(string ipAddress, int serverPort) { Log.Info("Initializing LiteNetLibClient..."); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); netPacketProcessor.SubscribeReusable <WrapperPacket, NetPeer>(OnPacketReceived); EventBasedNetListener listener = new EventBasedNetListener(); listener.PeerConnectedEvent += Connected; listener.PeerDisconnectedEvent += Disconnected; listener.NetworkReceiveEvent += ReceivedNetworkData; client = new NetManager(listener) { UpdateTime = 15, UnsyncedEvents = true, //experimental feature, may need to replace with calls to client.PollEvents(); #if DEBUG DisconnectTimeout = 300000 //Disables Timeout (for 5 min) for debug purpose (like if you jump though the server code) #endif }; client.Start(); client.Connect(ipAddress, serverPort, "nitrox"); connectedEvent.WaitOne(2000); connectedEvent.Reset(); }
public void StartServer() { DontDestroyOnLoad(gameObject); _logicTimer = new LogicTimer(OnLogicUpdate); _playerManager = new ServerPlayerManager(this); //_packetProcessor = new NetPacketProcessor(); ////register auto serializable vector2 //_packetProcessor.RegisterNestedType((w, v) => w.Put(v), r => r.GetVector2()); ////register auto serializable PlayerState //_packetProcessor.RegisterNestedType<PlayerState>(); //_packetProcessor.SubscribeReusable<JoinPacket, NetPeer>(OnJoinReceived); //_netManager = new NetManager(this) //{ // AutoRecycle = true //}; _netManager = G.CSEngineApp.LiteNet._netManager; _packetProcessor = G.CSEngineApp.LiteNet._packetProcessor; _packetProcessor.RegisterNestedType((w, v) => w.Put(v), r => r.GetVector2()); _packetProcessor.RegisterNestedType <PlayerState>(); _packetProcessor.SubscribeReusable <JoinPacket, NetPeer>(OnJoinReceived); _netManager.Start(10515); _logicTimer.Start(); }
public bool Start(NewPlayerInfo playerInfo, int port) { listener = new EventBasedNetListener(); server = new NetManager(listener); localPacketProcessor = new NetPacketProcessor(); Console.WriteLine("started instances..."); localPacketProcessor.SubscribeReusable <ZeroGPacket, NetPeer>(OnDataRecieve); if (!server.Start(port)) { Console.WriteLine("Failed to start server"); //return false; throw new Exception("Failed to start server..."); } newPlayerData = playerInfo; listener.ConnectionRequestEvent += Listener_ConnectionRequestEvent; listener.NetworkReceiveEvent += Listener_NetworkReceiveEvent; listener.PeerConnectedEvent += Listener_PeerConnectedEvent; listener.PeerDisconnectedEvent += Listener_PeerDisconnectedEvent; zeroPacketProcessor = new ProcessPacket(); InstanceKeeper.SetServerinstance(this); GetEvents(); // while (/*!Console.KeyAvailable*/1-1==0) //{ // server.PollEvents(); // Thread.Sleep(15); // } // this.server.Stop(); return(true); }
public Server() { server = new NetManager(this) { AutoRecycle = true, }; clients = new Dictionary <ushort, NebulaConnection>(); PacketProcessor = new NetPacketProcessor(); PacketProcessor.RegisterNestedType <NebulaId>(); PacketProcessor.RegisterNestedType <Float3>(); PacketProcessor.RegisterNestedType <Float4>(); PacketProcessor.RegisterNestedType <NebulaTransform>(); PacketProcessor.RegisterNestedType <NebulaAnimationState>(); PacketProcessor.SubscribeReusable <Movement, NebulaConnection> (OnPlayerMovement); PacketProcessor.SubscribeReusable <PlayerAnimationUpdate, NebulaConnection> (OnPlayerAnimationUpdate); PacketProcessor.SubscribeReusable <PlayerSpawned, NebulaConnection> (OnPlayerSpawned); }
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 ServerSerivce() { _serverManager = new ServerManager(); _logicTimer = new LogicTimer(OnUpdateLogic); _packetProcessor = new NetPacketProcessor(); _packetProcessor.RegisterNestedType((w, v) => w.Put(v), r => r.GetVector2()); _packetProcessor.RegisterNestedType <CharacterPacket>(); _packetProcessor.SubscribeReusable <JoinPacket, NetPeer>(OnJoin); _netManager = new NetManager(this, true); }
// Start is called before the first frame update void Start() { writer = new NetDataWriter(); packetProcessor = new NetPacketProcessor(); packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2()); // Will reuse the same packet class instance instead of creating new ones, so make sure to not store references to it or its contents! packetProcessor.SubscribeReusable <JoinPacket, NetPeer>(OnJoinReceived); packetProcessor.SubscribeReusable <PlayerSendUpdatePacket, NetPeer>(OnPlayerUpdate); // Registering the custom INetSerializable struct in the packet processor packetProcessor.RegisterNestedType <PlayerState>(); packetProcessor.RegisterNestedType <ClientPlayer>(); server = new NetManager(this) { AutoRecycle = true, }; }
public void Connect(string endpoint, int port) { if (manager != null) { throw new InvalidOperationException(); } var listener = new EventBasedNetListener(); manager = new NetManager(listener); manager.Start(); manager.Connect(endpoint, port, nameof(MultiplayerTest)); listener.PeerConnectedEvent += peer => server = peer; var processor = new NetPacketProcessor(); processor.RegisterNestedType <Order>(() => new Order()); processor.SubscribeReusable <OrderPacket>(packet => { foreach (var order in packet.Orders) { OrderReceived?.Invoke(order); } }); listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) => { var type = (PacketType)dataReader.GetByte(); switch (type) { case PacketType.StartGame: var players = dataReader.GetInt(); GameStarted?.Invoke(players); break; case PacketType.Orders: processor.ReadAllPackets(dataReader); break; } dataReader.Recycle(); }; writer = new NetDataWriter(); thread = new Thread(Run) { IsBackground = true }; thread.Start(); }
public ClientService(ActionService actionService, CharacterService characterService, Transform stage) { _clientManager = new ClientManager(actionService, characterService, stage); _cachedServerState = new ServerStatePacket(); _writer = new NetDataWriter(); _packetProcessor = new NetPacketProcessor(); _packetProcessor.RegisterNestedType((writer, v) => writer.Put(v), reader => reader.GetVector2()); _packetProcessor.RegisterNestedType <CharacterPacket>(); _packetProcessor.SubscribeReusable <CharacterJoinedPacket>(OnPlayerJoined); _packetProcessor.SubscribeReusable <PlayerLeavedPacket>(OnPlayerLeaved); _packetProcessor.SubscribeReusable <JoinAcceptPacket>(OnJoinAccept); var rand = new Random(); _userName = $"{Environment.MachineName} {rand.Next(100000)}"; _netManager = new NetManager(this, true); _netManager.Start(); LogicTimer = new LogicTimer(OnUpdateLogic); }
public void Connect(string ip, string username) { player.username = username; writer = new NetDataWriter(); packetProcessor = new NetPacketProcessor(); packetProcessor.RegisterNestedType((w, v) => w.Put(v), reader => reader.GetVector2()); packetProcessor.RegisterNestedType <PlayerState>(); packetProcessor.RegisterNestedType <ClientPlayer>(); packetProcessor.SubscribeReusable <JoinAcceptPacket>(OnJoinAccept); packetProcessor.SubscribeReusable <PlayerReceiveUpdatePacket>(OnReceiveUpdate); packetProcessor.SubscribeReusable <PlayerJoinedGamePacket>(OnPlayerJoin); packetProcessor.SubscribeReusable <PlayerLeftGamePacket>(OnPlayerLeave); client = new NetManager(this) { AutoRecycle = true, }; client.Start(); Debug.Log("Connecting to server"); client.Connect(ip, 12345, ""); }
public LobbyManager(Game game) { _game = game; _listener = new EventBasedNetListener(); _manager = new NetManager(_listener) { BroadcastReceiveEnabled = true, ReuseAddress = true }; _processor = new NetPacketProcessor(); _processor.SubscribeReusable <LobbyBroadcastPacket, IPEndPoint>(LobbyBroadcastReceived); _listener.NetworkReceiveUnconnectedEvent += NetworkReceiveUnconnectedEvent; }
public void Initialize() { lockList = new List <string>(); processor = new NetPacketProcessor(); otherPlayers = new Dictionary <string, Player>(); var listener = new EventBasedNetListener(); client = new NetManager(listener); processor.SubscribeReusable <Packet, NetPeer>(OnPacketReceive); client.Start(); listener.NetworkReceiveEvent += OnReceive; connectionThread = GetConnectionThread(); connectionThread.Start(); }
public Client() { EventBasedNetListener listener = new EventBasedNetListener(); listener.PeerConnectedEvent += OnPeerConnected; listener.PeerDisconnectedEvent += OnPeerDisconnected; listener.NetworkReceiveEvent += OnNetworkReceive; client = new NetManager(listener) { AutoRecycle = true, }; PacketProcessor = new NetPacketProcessor(); LiteNetLibUtils.RegisterAllPacketNestedTypes(PacketProcessor); PacketProcessor.SubscribeReusable <JoinSessionConfirmed>((_) => { IsSessionJoined = true; }); }
private void Awake() { DontDestroyOnLoad(gameObject); _logicTimer = new LogicTimer(OnLogicUpdate); _packetProcessor = new NetPacketProcessor(); _playerManager = new ServerPlayerManager(this); //register auto serializable vector2 _packetProcessor.RegisterNestedType((w, v) => w.Put(v), r => r.GetVector2()); //register auto serializable PlayerState _packetProcessor.RegisterNestedType <PlayerState>(); _packetProcessor.SubscribeReusable <JoinPacket, NetPeer>(OnJoinReceived); _netManager = new NetManager(this) { AutoRecycle = true }; }
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 NetClient() { _processor = new NetPacketProcessor(); _processor.RegisterNestedType <PlayersInRoomStruct>(); _processor.RegisterNestedType <PointStruct>(); _processor.SubscribeReusable <ServerPacket, NetPeer>(HandleServerCommand); _processor.SubscribeReusable <RoomPacket, NetPeer>(HandleRoomCommand); _processor.SubscribeReusable <PlayerPacket, NetPeer>(HandlePlayerCommand); _processor.SubscribeReusable <RoomReadyPacket, NetPeer>(HandleRoomReadyPacket); _processor.SubscribeReusable <GamePacket, NetPeer>(HandleGamePacket); _processor.SubscribeReusable <TurnPacket, NetPeer>(HandleTurn); }