private void Run() { SetSynchronizationContext(); _peer.RegisterReceivedCallback(MessageReady); _semaphore.Wait(); _peer.UnregisterReceivedCallback(MessageReady); }
/// <summary> /// Creates and starts a new NetworkPeer object, for servers. /// </summary> /// <param name="port">The port the server should listen on.</param> /// <param name="protocols">An array of messaging protocols.</param> public NetworkPeer(int port, params Protocol[] protocols) { Protocols = new List <Protocol>(protocols); netPeer = new NetPeer(new NetPeerConfiguration("N/A").GetStandardConfiguration(port)); netPeer.RegisterReceivedCallback(OnMessageReceivedCallback); Start(); }
public static void Start() { Peers = new ConcurrentDictionary <long, KulamiPeer>(); NetPeerConfiguration netPeerConfiguration = new NetPeerConfiguration("HelloWorld Kulami") { AcceptIncomingConnections = true, AutoFlushSendQueue = true, PingInterval = 1f, //ResendHandshakeInterval = 1f, ConnectionTimeout = 7, Port = Port, UseMessageRecycling = false, MaximumHandshakeAttempts = 100 }; netPeerConfiguration.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); netPeerConfiguration.EnableMessageType(NetIncomingMessageType.DiscoveryResponse); netPeerConfiguration.EnableMessageType(NetIncomingMessageType.UnconnectedData); netPeerConfiguration.EnableMessageType(NetIncomingMessageType.StatusChanged); Client = new NetPeer(netPeerConfiguration); Client.RegisterReceivedCallback(on_received_mesage); Client.Start(); TraceHelper.WriteLine("Personal ID: {0}", Client.UniqueIdentifier); TraceHelper.WriteLine("Broadcast: {0}", netPeerConfiguration.BroadcastAddress); // Broadcast thread new Thread(() => { while (true) { Client.DiscoverLocalPeers(Port); Thread.Sleep(2000); } }) { IsBackground = true }.Start(); // Message queue new Thread(() => { while (true) { Thread.Sleep(100); // Loop through the clients, and tell them to send what's in their queue foreach (KulamiPeer peer in Peers.Values) { peer.FlushQueue(); } } }) { IsBackground = true }.Start(); }
public virtual void Start() { Logger.LogInformation("Peer starting"); NetPeer = GetPeer(); NetPeer.RegisterReceivedCallback(ProcessMessage); NetPeer.Start(); Logger.LogInformation("Peer started"); }
public Peer(Handler handler, Config config) { IsAlive = false; _handler = handler; #region Config NetPeerConfiguration netConfig = new NetPeerConfiguration(config.AppId) { AutoExpandMTU = false, AutoFlushSendQueue = true, AcceptIncomingConnections = true, EnableUPnP = false, NetworkThreadName = "MonoLightTech.UnityNetwork.P2P", UseMessageRecycling = true, DefaultOutgoingMessageCapacity = Environment.ProcessorCount * 2, Port = config.Port, MaximumHandshakeAttempts = config.MaximumHandshakeAttempts, ResendHandshakeInterval = config.ResendHandshakeInterval, MaximumConnections = config.MaximumConnections, ConnectionTimeout = config.ConnectionTimeout, PingInterval = config.PingInterval, MaximumTransmissionUnit = config.MaximumTransmissionUnit, RecycledCacheMaxCount = config.MessageCacheSize }; #region Messages foreach (NetIncomingMessageType type in Enum.GetValues(typeof(NetIncomingMessageType))) { netConfig.DisableMessageType(type); } netConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval); netConfig.EnableMessageType(NetIncomingMessageType.StatusChanged); netConfig.EnableMessageType(NetIncomingMessageType.Data); netConfig.EnableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated); netConfig.EnableMessageType(NetIncomingMessageType.UnconnectedData); netConfig.EnableMessageType(NetIncomingMessageType.DebugMessage); netConfig.EnableMessageType(NetIncomingMessageType.WarningMessage); netConfig.EnableMessageType(NetIncomingMessageType.ErrorMessage); #endregion #endregion _peer = new NetPeer(netConfig); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); _peer.RegisterReceivedCallback(_Callback); _clients = new List <Connection>(); _clientsCache = new Connection[0]; _auths = new List <Pair <IPEndPoint, string> >(); _authsCache = new Pair <IPEndPoint, string> [0]; }
/// <summary> /// Initializes the server /// </summary> private void InitServer() { // Create a new net config NetPeerConfiguration netConfig = new NetPeerConfiguration(NetSettings.APP_IDENTIFIER); myAddress = NetUtils.GetAddress(); // Allow incoming connections netConfig.AcceptIncomingConnections = true; // Set the ping interval netConfig.PingInterval = NetSettings.DEFAULT_SERVER_TIMEOUT / 10.0f; // Set the address netConfig.LocalAddress = myAddress; // Set the timeout between heartbeats before a client is considered disconnected netConfig.ConnectionTimeout = NetSettings.DEFAULT_SERVER_TIMEOUT; // Set the maximum number of connections to the number of players netConfig.MaximumConnections = myPlayers.Count; // Set the port to use netConfig.Port = NetUtils.GetOpenPort(NetSettings.DEFAULT_SERVER_PORT + 1); // We want to recycle old messages (improves performance) netConfig.UseMessageRecycling = true; // We want to accept Connection Approval messages (requests for connection) netConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval); // We want to accept data (duh) netConfig.EnableMessageType(NetIncomingMessageType.Data); // We want to accept discovery requests netConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); // We want to accept status change messages (client connect / disconnect) netConfig.EnableMessageType(NetIncomingMessageType.StatusChanged); // We want the connection latency updates (heartbeats) netConfig.EnableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated); myNetConfig = netConfig; // Create the network peer myServer = new NetServer(netConfig); // Register the callback function. Lidgren will handle the threading for us myServer.RegisterReceivedCallback(new SendOrPostCallback(MessageReceived)); // Collect the rule types from tis assembly LoadRules(); // Add the message handlers... Would be nicer w/ reflection and custom attributes, but whatever myMessageHandlers.Add(MessageType.SendMove, HandleGameMove); myMessageHandlers.Add(MessageType.HostReqStart, HandleHostReqStart); myMessageHandlers.Add(MessageType.RequestServerState, HandleStateRequest); myMessageHandlers.Add(MessageType.PlayerReady, HandlePlayerReady); myMessageHandlers.Add(MessageType.HostReqAddBot, HandleHostReqBot); myMessageHandlers.Add(MessageType.HostReqKick, HandleHostReqKick); myMessageHandlers.Add(MessageType.PlayerChat, HandlePlayerChat); myMessageHandlers.Add(MessageType.RequestState, HandleGameStateRequest); myMessageHandlers.Add(MessageType.HostReqBotSettings, HandleHostReqBotSettings); }
public static int StartConnection() { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); NetPeerConfiguration config = new NetPeerConfiguration("GTAVOnlineRaces"); config.Port = new Random().Next(1000, 9999); peer = new NetPeer(config); peer.Start(); peer.RegisterReceivedCallback(ProcessMessages, SynchronizationContext.Current); return(1); }
public void StartClient(int fromPortNumber, String RemoteIPAddress, int RemotePort) { //TODO: test this and remove the start client string myEndpoint2 = new IPEndPoint(IPAddress.Parse(RemoteIPAddress), RemotePort); myConfig.Port = fromPortNumber; myPeer = new NetPeer(myConfig); SynchronizationContext myContext = new SynchronizationContext(); SynchronizationContext.SetSynchronizationContext(myContext); myPeer.RegisterReceivedCallback(ProcessIncoming, SynchronizationContext.Current); myPeer.Start(); myTimer = new Timer(new TimerCallback(AttemptToReconnect), this, 0, 500); }
public NetworkManager() { Conf = new NetPeerConfiguration("P2P"); Conf.EnableMessageType(NetIncomingMessageType.UnconnectedData); Conf.EnableMessageType(NetIncomingMessageType.ConnectionApproval); Conf.AcceptIncomingConnections = true; Conf.Port = 57300; Peer = new NetPeer(Conf); m_SyncContext = new SynchronizationContext(); SynchronizationContext.SetSynchronizationContext(m_SyncContext); Peer.RegisterReceivedCallback(new SendOrPostCallback(OnMessageReceived), SynchronizationContext.Current); Peer.Start(); Logman.Log("Network manager done loading. Ready to receive messages."); }
public HttpServer(Node r, int p) { root = r; listenerHttpPort = p; //JSON node count. nodeCount = 0; listener = new HttpListener(); NetPeerConfiguration config = new NetPeerConfiguration("OpenHardwareMonitor"); config.Port = p + 1; config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse); config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); peer = new NetPeer(config); peer.RegisterReceivedCallback(new SendOrPostCallback(HandlePeerMessages)); peerTimer = new System.Timers.Timer(); peerTimer.Elapsed += new ElapsedEventHandler(TimerElapsed); peerTimer.Interval = 1000 * 60 * 1; }
public LidgrenInterface(INetwork network, Type peerType, RSAParameters rsaParameters) { if (peerType == null) { throw new ArgumentNullException(nameof(peerType)); } mNetwork = network ?? throw new ArgumentNullException(nameof(network)); var configuration = mNetwork.Configuration; if (configuration == null) { throw new ArgumentNullException(nameof(mNetwork.Configuration)); } mRng = new RNGCryptoServiceProvider(); mRsa = new RSACryptoServiceProvider(); mRsa.ImportParameters(rsaParameters); mPeerConfiguration = new NetPeerConfiguration( $"{VersionHelper.ExecutableVersion} {VersionHelper.LibraryVersion} {SharedConstants.VersionName}" ) { AcceptIncomingConnections = configuration.IsServer }; mPeerConfiguration.DisableMessageType(NetIncomingMessageType.Receipt); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.UnconnectedData); if (configuration.IsServer) { mPeerConfiguration.EnableMessageType(NetIncomingMessageType.DiscoveryRequest); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.ConnectionApproval); mPeerConfiguration.AcceptIncomingConnections = true; mPeerConfiguration.MaximumConnections = configuration.MaximumConnections; //mPeerConfiguration.LocalAddress = DnsUtils.Resolve(config.Host); //mPeerConfiguration.EnableUPnP = true; mPeerConfiguration.Port = configuration.Port; } if (Debugger.IsAttached) { mPeerConfiguration.EnableMessageType(NetIncomingMessageType.DebugMessage); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.ErrorMessage); mPeerConfiguration.EnableMessageType(NetIncomingMessageType.Error); } else { mPeerConfiguration.DisableMessageType(NetIncomingMessageType.DebugMessage); mPeerConfiguration.DisableMessageType(NetIncomingMessageType.ErrorMessage); mPeerConfiguration.DisableMessageType(NetIncomingMessageType.Error); } if (Debugger.IsAttached) { mPeerConfiguration.ConnectionTimeout = 60; mPeerConfiguration.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); } else { mPeerConfiguration.ConnectionTimeout = 15; mPeerConfiguration.DisableMessageType(NetIncomingMessageType.VerboseDebugMessage); } mPeerConfiguration.PingInterval = 2.5f; mPeerConfiguration.UseMessageRecycling = true; var constructorInfo = peerType.GetConstructor(new[] { typeof(NetPeerConfiguration) }); if (constructorInfo == null) { throw new ArgumentNullException(nameof(constructorInfo)); } var constructedPeer = constructorInfo.Invoke(new object[] { mPeerConfiguration }) as NetPeer; mPeer = constructedPeer ?? throw new ArgumentNullException(nameof(constructedPeer)); mGuidLookup = new Dictionary <long, Guid>(); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); mPeer?.RegisterReceivedCallback( peer => { lock (mPeer) { if (OnPacketAvailable == null) { Log.Debug("Unhandled inbound Lidgren message."); Log.Diagnostic($"Unhandled message: {TryHandleInboundMessage()}"); return; } OnPacketAvailable(this); } } ); }
public void Start(NetPeerConfiguration config) { LidgrenPeer = new NetPeer(config); LidgrenPeer.RegisterReceivedCallback(_messageReadyCallback); LidgrenPeer.Start(); }
/// <summary> /// Initializes a client /// </summary> private void Initialize() { // Create a new net config NetPeerConfiguration netConfig = new NetPeerConfiguration(NetSettings.APP_IDENTIFIER); // Gets the IP for this client myAddress = NetUtils.GetAddress(); // Create the dictionary myMessageHandlers = new Dictionary <MessageType, PacketHandler>(); // Make the local game state myLocalState = new GameState(); // Make the player collection myKnownPlayers = new PlayerCollection(); // Define the hand myHand = new CardCollection(); // Allow incoming connections netConfig.AcceptIncomingConnections = true; // Set the ping interval netConfig.PingInterval = NetSettings.DEFAULT_SERVER_TIMEOUT / 10.0f; // Set the address netConfig.LocalAddress = myAddress; // Set the timeout between heartbeats before a client is considered disconnected netConfig.ConnectionTimeout = NetSettings.DEFAULT_SERVER_TIMEOUT; // Set the port to use netConfig.Port = NetUtils.GetOpenPort(NetSettings.DEFAULT_SERVER_PORT + 1); // We want to recycle old messages (improves performance) netConfig.UseMessageRecycling = true; // We want to accept Connection Approval messages (requests for connection) netConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval); // We want to accept data (duh) netConfig.EnableMessageType(NetIncomingMessageType.Data); // We want to accept status change messages (client connect / disconnect) netConfig.EnableMessageType(NetIncomingMessageType.StatusChanged); // We want the connection latency updates (heartbeats) netConfig.EnableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated); // Create the network peer myPeer = new NetServer(netConfig); // Register the callback function. Lidgren will handle the threading for us myPeer.RegisterReceivedCallback(new SendOrPostCallback(MessageReceived)); // Add all the handlers myMessageHandlers.Add(MessageType.PlayerConnectInfo, HandleConnectInfo); myMessageHandlers.Add(MessageType.GameStateChanged, HandleStateChanged); myMessageHandlers.Add(MessageType.FullGameStateTransfer, HandleStateReceived); myMessageHandlers.Add(MessageType.InvalidServerState, HandleInvalidServerState); myMessageHandlers.Add(MessageType.NotifyServerStateChanged, HandleServerStateReceived); myMessageHandlers.Add(MessageType.PlayerJoined, HandlePlayerJoined); myMessageHandlers.Add(MessageType.PlayerLeft, HandlePlayerLeft); myMessageHandlers.Add(MessageType.PlayerKicked, HandlePlayerKicked); myMessageHandlers.Add(MessageType.SucessfullMove, HandleMoveReceived); myMessageHandlers.Add(MessageType.InvalidMove, HandleInvalidMove); myMessageHandlers.Add(MessageType.PlayerChat, HandlePlayerChat); myMessageHandlers.Add(MessageType.PlayerReady, HandlePlayerReady); myMessageHandlers.Add(MessageType.CardCountChanged, HandleCardCountChanged); myMessageHandlers.Add(MessageType.PlayerHandChanged, HandleCardChanged); myMessageHandlers.Add(MessageType.CannotStart, HandleCannotStart); myMessageHandlers.Add(MessageType.HostReqBotSettings, HandleBotSettingsChanged); }
public void Start(NetPeer knowPeer, string masterServerAdress, int masterServerPort, object caller) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); entitySystem = new UnityActor.ActorSystem("entitySystem") { Options = new UnityActor.ActorSystemOptions() { MultipleSameIdAllowed = false, ThrowErrorOnExistingID = false, //: 1 } }; //: 1 // Cela permettra d'avoir plusieurs entités d'un même groupe sans problème // Puis de toute façon, il n y aura pas de problèmes avec les joueurs : // Ils seront remplacé. gameServer = this; UsingPeer = knowPeer; UsingPeer.RegisterReceivedCallback(new SendOrPostCallback((o) => { try { ReceiveIncomingMessage((NetPeer)o); } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}\n{ex.StackTrace}"); } })); UsingPeer.Start(); var hailMessage = UsingPeer.CreateMessage("CONNECT"); hailMessage.Write("GAMEROOM"); UsingPeer.Connect(masterServerAdress, masterServerPort, hailMessage); //peer.Connect("127.0.0.1", 7641); Time.StartTime = TimeSpan.Zero; Time.Timer = new System.Timers.Timer(10); Time.Timer.Elapsed += new System.Timers.ElapsedEventHandler((object obj, System.Timers.ElapsedEventArgs args) => { Time.LastTime = Time.TimeElapsed; Time.TickElapsed = args.SignalTime.Millisecond; }); Time.Timer.Enabled = true; if (caller != null && caller.GetType() == typeof(MonoBehaviour)) { caller.GetType().GetMethod("print").Invoke(this, new object[] { "started!" }); } bool createdNew; var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, (Guid.NewGuid().ToString() + Guid.NewGuid().ToString()), out createdNew); var signaled = false; //var timer = new Timer(, null, TimeSpan.Zero, TimeSpan.FromSeconds(10)); Console.Title = "Connecting"; while (UsingPeer.Status != NetPeerStatus.Running) { ; } //Room.hasLoaded = true; /*Log($@"Room info: * Creator Name: {Room.creatorName} * Room Description: {Room.description} * Adress: {Room.ipAdress}:{Room.port} * ");*/ /* var testMsg = UsingPeer.CreateMessage().Start(Constants.SYSTEM.DEBUG); * testMsg.Subscribe((netMsg) => Console.WriteLine("Seems like it worked, no?")); * * UsingPeer.SendUnconnectedToSelf(testMsg);*/ Console.WriteLine("ke"); timeLeft_BeforeShutdown = -1f; shutdownSent = false; currentGameState = EGameState.Basement; do { signaled = waitHandle.WaitOne(TimeSpan.FromSeconds(1f / FPS)); Update(); }while (!signaled && !stop); while (!shutdownSent) { ; } }