Exemple #1
0
 internal async Task ServerStoppedNotification(ServerStoppedNotification notification)
 {
     if (ServerStopped != null)
     {
         await ServerStopped?.Invoke(notification);
     }
 }
 public override void OnStopServer()
 {
     ServerStopped?.Invoke();
     RoomPlayers.Clear();
     GamePlayers.Clear();
     //base.OnStopServer();
 }
Exemple #3
0
 public void Start()
 {
     if (!File.Exists(UpdateFileLocation))
     {
         OnDebug("Update file \"" + UpdateFileLocation + "\" doesn't exist!");
     }
     else if (!IsListening)
     {
         IsListening = true;
         if (listenerSocket == null)
         {
             listenerSocket                     = new AsynchronousSocket();
             listenerSocket.Debug              += new TextEventHandler(listenerSocket_Debug);
             listenerSocket.ClientConnected    += new EventHandler(listenerSocket_ClientConnected);
             listenerSocket.IsListeningChanged += new EventHandler(listenerSocket_IsListeningChanged);
         }
         listenerSocket.Bind(IPAddress.Any, ListeningPort);
         listenerSocket.StartListening(); // Blocks until StopListening
     }
     IsListening = false;
     if (ServerStopped != null) // Thread is about to exit
     {
         ServerStopped.Invoke(this, new EventArgs());
     }
 }
Exemple #4
0
        public void Stop()
        {
            if (_server.IsRunning)
            {
                _server.Stop();
                _t.Join();
            }

            ServerStopped?.Invoke(this, EventArgs.Empty);
        }
        /// <summary>
        /// The thread method where the client listens for new messages and handles them accordingly.
        /// </summary>
        private void ListenForMessages()
        {
            var bytes = new List <byte>();

            while (!IsDisposed)
            {
                var i = -1;

                try
                {
                    i = _stream.ReadByte();
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.Interrupted)
                    {
                        break;
                    }
                }
                catch
                {
                    break;
                }

                if (i == -1)
                {
                    break;
                }
                else if (i == TcpOptions.EndMessageCode)
                {
                    if (bytes.Count > 0)
                    {
                        var message   = bytes.ToArray().GetString();
                        var eventargs = new MessageReceivedEventArgs
                        {
                            Message = message,
                            Time    = DateTime.Now,
                            Client  = this
                        };
                        MessageReceived?.Invoke(this, eventargs);
                        bytes.Clear();
                    }
                }
                else if (i == TcpOptions.EndConnectionCode && !IsServerClient)
                {
                    ServerStopped?.Invoke(this, null);
                    Dispose(true);
                    break;
                }
                else
                {
                    bytes.Add(Convert.ToByte(i));
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Shuts down the server
        /// </summary>
        public Task StopAsync()
        {
            Console.WriteLine(ResourceStrings.Server_StopAsync_Log);

            Running = false;
            ServerStopped?.Invoke();
            Certificate?.Dispose();
            Api?.Close();

            return(RakNetServer.ShutdownAsync());
        }
Exemple #7
0
        public Task StopAsync()
        {
            Logger.Log("Shutting down...");

            Running = false;

            ServerStopped?.Invoke();

            Certificate.Dispose();

            return(RakNetServer.ShutdownAsync());
        }
Exemple #8
0
        /// <summary>
        /// 停止运行
        /// </summary>
        public async Task StopAsync()
        {
            foreach (var item in channels)
            {
                await item.CloseAsync();
            }

            allSession.Clear();
            channels.Clear();
            stopTime = DateTime.Now;
            ServerStopped?.Invoke(this, new EventArgs());
            OnServerStopped();
        }
Exemple #9
0
        public void Stop()
        {
            if (!IsRunning)
            {
                return;
            }

            CancellationTokenSource.Cancel();
            Listener.Stop();

            IsRunning = false;
            ServerStopped?.Invoke(this, EventArgs.Empty);
        }
Exemple #10
0
        /// <summary>
        /// Disconnect from the network.
        /// </summary>
        public virtual void Disconnect()
        {
            if (!IsStarted)
            {
                return;
            }

            if (IsServer)
            {
                ServerStopped?.Invoke();
            }
            else
            {
                ConnectionTerminated?.Invoke();
            }

            m_LastSendSize           = 0;
            m_ReceiveBuffer          = null;
            IsConnected              = false;
            IsServer                 = false;
            IsStarted                = false;
            m_HostID                 = -1;
            ConnectionID             = -1;
            LocalConnectionID        = -1;
            ReliableChannel          = 0;
            UnReliableChannel        = 0;
            ReliableSequencedChannel = 0;
            m_ReceiveHandlers?.Clear();
            m_ReceiveHandlers = null;
            m_Connections?.Clear();
            m_Connections = null;
            Scene?.Clear();
            Scene = null;
            RemoteProcedures?.Clear();

            ConnectionEstablished    = null;
            ConnectionTerminated     = null;
            ServerClientConnected    = null;
            ServerClientDisconnected = null;
            RemoteConnected          = null;
            RemoteDisconnected       = null;
            OnlineSceneLoaded        = null;
            ServerStarted            = null;
            ServerStopped            = null;
            InitializeHandlers       = null;
            Log = null;

            NetworkTransport.Shutdown();
            SceneManager.LoadScene(m_Settings.m_OfflineScene.m_SceneName);
        }
Exemple #11
0
        private void OnServerStopped()
        {
            if (ServerStopped == null)
            {
                return;
            }

            Task.Run(() =>
            {
                ServerStopped?.Invoke(this, new InternetEventArgs {
                    Local = this
                });
            });
        }
Exemple #12
0
        public Task StopAsync()
        {
            Console.WriteLine("Shutting down...");

            Running = false;

            ServerStopped?.Invoke();

            Certificate?.Dispose();

            Api?.Close();

            return(RakNetServer.ShutdownAsync());
        }
        private void RaiseServerChangedEvent(MediaControllerNativeServerState state, MediaController controller)
        {
            if (controller == null)
            {
                return;
            }

            if (state == MediaControllerNativeServerState.Activated)
            {
                ServerStarted?.Invoke(this, new MediaControlServerStartedEventArgs(controller));
            }
            else
            {
                controller.RaiseStoppedEvent();
                ServerStopped?.Invoke(this, new MediaControlServerStoppedEventArgs(controller.ServerAppId));
            }
        }
Exemple #14
0
        /// <summary>
        /// Stop the TCP server.
        /// </summary>
        /// <remarks>
        /// Calling this function had no effect once server is stopped.
        /// </remarks>
        public void Stop()
        {
            if (ConnectionMonitoring == null)
            {
                return;
            }
            Trace.WriteLine(Name + ": Shutting Down TCP Server...");

            Abort = true;
            while (ConnectionMonitoring.IsAlive)
            {
                Thread.Sleep(10);
            }
            DisconnectAllClients();
            ConnectionMonitoring = null;
            ServerStopped?.Invoke(this, null);
        }
Exemple #15
0
        //Dedicate one thread to incoming connections
        private void ThreadListener()
        {
            try
            {
                ServerStarted?.Invoke();

                while (true)
                {
                    Socket hNewConnection = m_hListener.Accept(); //il thread sta in attesa per una connessione in ingresso

                    //T deve ricevere il socket, 2 modi: 1) T implementa un interfaccia interna, 2) creiamo un allocatore per T
                    T hConnHandler = new T();
                    hConnHandler.Socket = hNewConnection;
                    hConnHandler.CreateBuffer(m_iBufferSize);

                    lock (m_hConnections)
                    {
                        hConnHandler.Id    = s_iCounter;
                        hConnHandler.Owner = this;

                        m_hConnections.Add(hConnHandler.Id, hConnHandler);
                        s_iCounter++;                        
                    }

                    hConnHandler.BeginReceive(); //connection now active, let the user code handle requests and resposes

                    try
                    {
                        ClientConnected?.Invoke(hConnHandler);
                    }
                    catch (Exception)
                    {
                        //Se qualcuno nell'implementazione dell'evento fa danni... a noi non ci interessa
                    }
                }
            }
            catch (Exception)
            {
                //se siamo qui è xche abbiamo chiamato stop quindi possiamo interrompere il ciclo
                ServerStopped?.Invoke();                
            }
        }
Exemple #16
0
        private void ServerConnected(IAsyncResult ar)
        {
            lock (monitor) { tcpClient.EndConnect(ar); }
            new Thread(() =>
            {
                try
                {
                    NetworkStream stream;
                    lock (monitor)
                    {
                        stream = tcpClient.GetStream();
                        SendMessage(new WelcomePlumberIAm(Username));
                    }
                    Handle(ReadMessages <IToAlchemy>(stream));
                }
                catch (Exception ex) { Console.Error.WriteLine(ex.Message); } // <- Ugly game jam code

                lock (monitor) { tcpClient = null; }
                invoke(() => ServerStopped?.Invoke());
            }).Start();
        }
        /// <summary>
        /// 停止运行
        /// </summary>
        public void Stop()
        {
            if (IsRun)
            {
                Interlocked.Decrement(ref isRun);
            }
            try
            {
                listen?.Close();
                listen?.Shutdown(SocketShutdown.Both);
            }
            catch (Exception)
            {
            }

            listen = null;

            stopTime = DateTime.Now;
            ServerStopped?.Invoke(this, new EventArgs());
            OnServerStopped();
        }
Exemple #18
0
        public void Stop()
        {
            lock (this)
            {
                if (!Running)
                {
                    return;
                }

                Running = false;

                foreach (StreamSocketListener listener in socketListeners)
                {
                    listener.Dispose();
                }

                socketListeners.Clear();
                socketListeners = null;

                ServerStopped?.Invoke(this);
            }
        }
Exemple #19
0
        public void Stop()
        {
            if (!Running)
            {
                throw new InvalidOperationException("Server not running");
            }

            ISLogger.Write("Stopping server");

            foreach (ConnectedClient client in clientMan?.AllClients)
            {
                clientMan.RemoveClient(client);
                client.Dispose();
            }
            tcpListener?.Stop();

            if (inputMan.Running)
            {
                inputMan?.Stop();
            }
            inputMan = null;

            if (curMonitor.Running)
            {
                curMonitor?.Stop();
            }
            curMonitor = null;
            if (procMonitor.Monitoring)
            {
                procMonitor?.StopMonitoring();
            }

            procMonitor = null;
            tcpListener = null;
            Running     = false;
            ServerStopped?.Invoke(this, null);
        }
Exemple #20
0
        private async Task AcceptConnections()
        {
            string header = "[WatsonWsServer.AcceptConnections] ";

            try
            {
                _Listener.Start();

                while (!_Token.IsCancellationRequested)
                {
                    HttpListenerContext ctx = await _Listener.GetContextAsync();

                    string ip     = ctx.Request.RemoteEndPoint.Address.ToString();
                    int    port   = ctx.Request.RemoteEndPoint.Port;
                    string ipPort = ip + ":" + port;

                    lock (_PermittedIpsLock)
                    {
                        if (PermittedIpAddresses != null &&
                            PermittedIpAddresses.Count > 0 &&
                            !PermittedIpAddresses.Contains(ip))
                        {
                            Logger?.Invoke(header + "rejecting connection from " + ipPort + " (not permitted)");
                            ctx.Response.StatusCode = 401;
                            ctx.Response.Close();
                            continue;
                        }
                    }

                    if (!ctx.Request.IsWebSocketRequest)
                    {
                        if (HttpHandler != null)
                        {
                            Logger?.Invoke(header + "non-websocket request forwarded to HTTP handler from " + ipPort + ": " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl);
                            HttpHandler.Invoke(ctx);
                        }
                        else
                        {
                            Logger?.Invoke(header + "non-websocket request rejected from " + ipPort);
                            ctx.Response.StatusCode = 400;
                            ctx.Response.Close();
                        }

                        continue;
                    }

                    CancellationTokenSource tokenSource = new CancellationTokenSource();
                    CancellationToken       token       = tokenSource.Token;

                    await Task.Run(() =>
                    {
                        Logger?.Invoke(header + "starting data receiver for " + ipPort);

                        Task.Run(async() =>
                        {
                            WebSocketContext wsContext;
                            try
                            {
                                wsContext = await ctx.AcceptWebSocketAsync(subProtocol: null);
                            }
                            catch (Exception)
                            {
                                Logger?.Invoke(header + "unable to retrieve websocket content for client " + ipPort);
                                ctx.Response.StatusCode = 500;
                                ctx.Response.Close();
                                return;
                            }

                            WebSocket ws      = wsContext.WebSocket;
                            ClientMetadata md = new ClientMetadata(ctx, ws, wsContext, tokenSource);

                            _Clients.TryAdd(md.IpPort, md);
                            ClientConnected?.Invoke(this, new ClientConnectedEventArgs(md.IpPort, ctx.Request));
                            await Task.Run(() => DataReceiver(md), token);
                        }, token);
                    }, _Token);
                }
            }
            catch (HttpListenerException)
            {
                // can be thrown when disposed
            }
            catch (OperationCanceledException)
            {
                // thrown when disposed
            }
            catch (Exception e)
            {
                Logger?.Invoke(header + "exception:" + Environment.NewLine + e.ToString());
            }
            finally
            {
                ServerStopped?.Invoke(this, EventArgs.Empty);
            }
        }
Exemple #21
0
        private async Task AcceptConnections()
        {
            try
            {
                _Listener.Start();

                while (true)
                {
                    if (_Token.IsCancellationRequested)
                    {
                        break;
                    }
                    if (!_Listener.IsListening)
                    {
                        Task.Delay(100).Wait();
                        continue;
                    }

                    HttpListenerContext ctx = await _Listener.GetContextAsync();

                    string ip     = ctx.Request.RemoteEndPoint.Address.ToString();
                    int    port   = ctx.Request.RemoteEndPoint.Port;
                    string ipPort = ip + ":" + port;

                    lock (_PermittedIpsLock)
                    {
                        if (PermittedIpAddresses != null &&
                            PermittedIpAddresses.Count > 0 &&
                            !PermittedIpAddresses.Contains(ip))
                        {
                            Logger?.Invoke(_Header + "rejecting " + ipPort + " (not permitted)");
                            ctx.Response.StatusCode = 401;
                            ctx.Response.Close();
                            continue;
                        }
                    }

                    if (!ctx.Request.IsWebSocketRequest)
                    {
                        if (HttpHandler == null)
                        {
                            Logger?.Invoke(_Header + "non-websocket request rejected from " + ipPort);
                            ctx.Response.StatusCode = 400;
                            ctx.Response.Close();
                        }
                        else
                        {
                            Logger?.Invoke(_Header + "non-websocket request from " + ipPort + " HTTP-forwarded: " + ctx.Request.HttpMethod.ToString() + " " + ctx.Request.RawUrl);
                            HttpHandler.Invoke(ctx);
                        }

                        continue;
                    }
                    else
                    {
                        /*
                         * HttpListenerRequest req = ctx.Request;
                         * Console.WriteLine(Environment.NewLine + req.HttpMethod.ToString() + " " + req.RawUrl);
                         * if (req.Headers != null && req.Headers.Count > 0)
                         * {
                         *  Console.WriteLine("Headers:");
                         *  var items = req.Headers.AllKeys.SelectMany(req.Headers.GetValues, (k, v) => new { key = k, value = v });
                         *  foreach (var item in items)
                         *  {
                         *      Console.WriteLine("  {0}: {1}", item.key, item.value);
                         *  }
                         * }
                         */
                    }

                    await Task.Run(() =>
                    {
                        Logger?.Invoke(_Header + "starting data receiver for " + ipPort);

                        CancellationTokenSource tokenSource = new CancellationTokenSource();
                        CancellationToken token             = tokenSource.Token;

                        Task.Run(async() =>
                        {
                            WebSocketContext wsContext = await ctx.AcceptWebSocketAsync(subProtocol: null);
                            WebSocket ws      = wsContext.WebSocket;
                            ClientMetadata md = new ClientMetadata(ctx, ws, wsContext, tokenSource);

                            _Clients.TryAdd(md.IpPort, md);

                            ClientConnected?.Invoke(this, new ClientConnectedEventArgs(md.IpPort, ctx.Request));
                            await Task.Run(() => DataReceiver(md), token);
                        }, token);
                    }, _Token);
                }
            }
            catch (HttpListenerException)
            {
                // thrown when disposed
            }
            catch (OperationCanceledException)
            {
                // thrown when disposed
            }
            catch (ObjectDisposedException)
            {
                // thrown when disposed
            }
            catch (Exception e)
            {
                Logger?.Invoke(_Header + "listener exception:" + Environment.NewLine + e.ToString());
            }
            finally
            {
                ServerStopped?.Invoke(this, EventArgs.Empty);
            }
        }
Exemple #22
0
 protected virtual void OnServerDisconnected()
 {
     ServerStopped?.Invoke(this, EventArgs.Empty);
 }
Exemple #23
0
 internal void HandleServerStopped(object sender, EventArgs args)
 {
     WrappedEventHandler(() => ServerStopped?.Invoke(sender, args), "ServerStopped", sender);
 }
Exemple #24
0
 internal void RaiseStoppedEvent()
 {
     IsStopped = true;
     ServerStopped?.Invoke(this, EventArgs.Empty);
 }
 internal void HandleServerStopped(object sender, EventArgs args)
 {
     ServerStopped?.Invoke(sender, args);
 }
Exemple #26
0
        private void Listen()
        {
            IPAddress adress = IPAddress.Parse(_mainHost);

            using (_mainSocket = new Socket(adress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                _mainSocket.Bind(new IPEndPoint(adress, _mainPort));
                _mainSocket.Listen(100);
                _isWork = true;
                ServerStarted?.Invoke();
                ConnectionsChange?.Invoke(clients.Count);
                while (!_tryStop)
                {
                    Socket clientSocket = _mainSocket.Accept();
                    lock (clients)
                    {
                        clients.Add(new ServerClient(clientSocket,
                                                     (disconnectedClient) =>
                        {
                            lock (clients)
                            {
                                if (clients.Contains(disconnectedClient) && !_tryStop)
                                {
                                    clients.Remove(disconnectedClient);
                                    if (disconnectedClient.UserName != "")
                                    {
                                        ClientLogoutEvent?.Invoke(disconnectedClient.UserName);
                                    }
                                }
                                ConnectionsChange?.Invoke(clients.Count);
                            }
                        },
                                                     (header, sendedToAllData) =>
                        {
                            lock (clients)
                            {
                                foreach (ServerClient client in clients)
                                {
                                    client.SendData(header, sendedToAllData);
                                }
                            }
                        },
                                                     (header, sendToUserData, userName) =>
                        {
                            lock (clients)
                            {
                                clients.FirstOrDefault(c => c.UserName == userName)?.SendData(header, sendToUserData);
                            }
                        },
                                                     (userName) =>
                        {
                            lock (clients)
                            {
                                if (clients.FirstOrDefault(c => c.UserName == userName) == null)
                                {
                                    ClientLoginEvent?.Invoke(userName);
                                    return(true);
                                }
                            }
                            return(false);
                        }));

                        ConnectionsChange?.Invoke(clients.Count);
                    }
                }
                lock (clients)
                {
                    foreach (ServerClient c in clients)
                    {
                        c.Disconnect();
                    }
                    clients.Clear();
                }
                //_mainSocket.Shutdown(SocketShutdown.Both);
                _mainSocket.Close();
                _isWork = false;
                ServerStopped?.Invoke();
            }
        }
Exemple #27
0
 private void ServerInstance_Stopped(object sender, EventArgs e)
 {
     ServerStopped?.Invoke(this, null);
 }
Exemple #28
0
 protected void OnServerStopped()
 {
     ServerStopped?.Invoke(mvarID);
 }