示例#1
0
        private void OnServerStopped(ServerStopped ev)
        {
            _mainModel.Connections.ClearAllConnections();

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                _mainModel.StatusBar.CurrentStatus = "Stopped.";
                _mainModel.Info.StopUptimeCounter();

            }));
        }
 internal void HandleServerStopped(object sender, EventArgs args)
 {
     ServerStopped?.Invoke(sender, args);
 }
示例#3
0
 public void ServerStop()
 {
     ServerStopped.Add(Now);
 }
 internal void HandleServerStopped(object sender, EventArgs args)
 {
     WrappedEventHandler(() => ServerStopped?.Invoke(sender, args), "ServerStopped", sender);
 }
示例#5
0
        private async Task AcceptConnections(CancellationToken cancelToken)
        {
            try
            {
                while (!cancelToken.IsCancellationRequested)
                {
                    if (!_Listener.IsListening)
                    {
                        Task.Delay(100).Wait();
                        continue;
                    }

                    HttpListenerContext ctx = await _Listener.GetContextAsync().ConfigureAwait(false);

                    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).ConfigureAwait(false);
                }
            }

            /*
             * catch (HttpListenerException)
             * {
             *  // thrown when disposed
             * }
             */
            catch (TaskCanceledException)
            {
                // 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);
            }
        }
 protected virtual void OnServerStopped()
 {
     ServerStopped?.Invoke(this, EventArgs.Empty);
 }
示例#7
0
 protected void OnServerStopped()
 {
     ServerStopped?.Invoke(mvarID);
 }
示例#8
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();
            }
        }
 internal void RaiseStoppedEvent()
 {
     IsStopped = true;
     ServerStopped?.Invoke(this, EventArgs.Empty);
 }
示例#10
0
 private void ServerInstance_Stopped(object sender, EventArgs e)
 {
     ServerStopped?.Invoke(this, null);
 }