Example #1
0
        static void Main(string[] args)
        {
            WsServer.Start();

            Console.WriteLine("Listening...");
            Console.ReadLine();
        }
Example #2
0
        public NetworkManager()
        {
            SettingsManager settingsManager = new SettingsManager("C:\\Users\\VasyutkinKP\\Documents\\GitHub\\Pet-project\\Server\\bin\\Debug\\ServerConfig.xml");

            _transport        = settingsManager.Transport;
            _ip               = settingsManager.Ip;
            _port             = settingsManager.Port;
            _timeout          = settingsManager.Timeout;
            _connectionString = settingsManager.ConnectionSettings;

            DatabaseController databaseController = new DatabaseController(_connectionString);

            if (_transport == "WebSocket")
            {
                _wsServer = new WsServer(new IPEndPoint(_ip, _port));
                _wsServer.ConnectionStateChanged += HandleConnectionStateChanged;
                _wsServer.ConnectionReceived     += HandleConnectionReceived;
                _wsServer.MessageReceived        += HandleMessageReceived;
                _wsServer.ErrorReceived          += HandleErrorReceived;
                _wsServer.FilterReceived         += HandleFilterReceived;
                _wsServer.CreateGroupReceived    += HandleCreateGroupReceived;
                _wsServer.LeaveGroupReceived     += HandleLeaveGroupReceived;
                _wsServer.Timeout = _timeout;
            }

            _txtMsgService      = new TextMessageService(databaseController);
            _clientEventService = new ClientEventService(databaseController);
            _clientService      = new ClientService(databaseController);
            _groupService       = new GroupService(databaseController);
        }
Example #3
0
        private void TryGetLevel()
        {
            if (Level != null)
            {
                return;
            }

            var lm = _server.LevelManager;

            if (lm == null)
            {
                return;
            }

            Level = lm.Levels.FirstOrDefault(l => l != null &&
                                             l.LevelId.Equals(Map.Config.LevelId,
                                                              StringComparison.InvariantCultureIgnoreCase));

            if (Level != null)
            {
                WsServer.BroadcastPacket(new LevelMetaPacket()
                {
                    LevelId = Level.LevelId,
                    Meta    = Map.Meta
                });
            }
        }
Example #4
0
        public NetworkManager(
            string address,
            int port,
            int timeOut,
            string dataBaseConnectionString,
            IRepository <ClientDto> clientDataBase,
            IRepository <MessageDto> msgDataBase,
            IRepository <EventDto> eventDataBase)
        {
            if (string.IsNullOrEmpty(address))
            {
                _wsServer = new WsServer(new IPEndPoint(IPAddress.Any, port), timeOut, clientDataBase, msgDataBase, eventDataBase);
            }
            else
            {
                var           dataBaseConnectionSettings = new ConnectionStringSettings("DBConnection", dataBaseConnectionString, "System.Data.SqlClient");
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings.Clear();
                config.ConnectionStrings.ConnectionStrings.Add(dataBaseConnectionSettings);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.Name);

                int       wsPort    = Convert.ToInt32(port);
                IPAddress ipAddress = IPAddress.Parse(address);
                byte[]    bytes     = ipAddress.GetAddressBytes();
                uint      wsAddress = BitConverter.ToUInt32(bytes, 0);

                _wsServer = new WsServer(new IPEndPoint(wsAddress, wsPort), Convert.ToInt32(timeOut), clientDataBase, msgDataBase, eventDataBase);
            }
        }
Example #5
0
 public void Stop()
 {
     _host.Dispose();
     WsServer.Stop();
     _proxy.Dispose();
     Log.InfoFormat("Web server stopped.");
 }
Example #6
0
 public NetworkManager(
     IRepository <ClientDto> clientDataBase,
     IRepository <MessageDto> msgDataBase,
     IRepository <EventDto> eventDataBase)
 {
     _wsServer = new WsServer(new IPEndPoint(IPAddress.Any, WS_PORT), TIME_OUT, clientDataBase, msgDataBase, eventDataBase);
 }
Example #7
0
        public async Task ValidateCryptoHandshake()
        {
            var     server = new WsServer();
            var     serverKey = CryptoExtensions.GenerateKey();
            var     clientKey = CryptoExtensions.GenerateKey();
            ECPoint serverPub, clientPub = new ECPoint();
            await server.StartAsync(new IPEndPoint(IPAddress.Loopback, 0), async stream =>
            {
                clientPub = await stream.EncryptAsync(serverKey);
            });

            await Task.Delay(500);

            // start client
            var client = new WsClient();
            var conn   = await client.ConnectAsync(new Uri($"ws://" + server.ListeningAddresses[0].Substring(7)));

            serverPub = await conn.EncryptAsync(clientKey);

            await Task.Delay(500);

            Assert.Equal(serverKey.Q.X, serverPub.X);
            Assert.Equal(clientKey.Q.X, clientPub.X);
            server.Dispose();
            client.Dispose();
        }
        public static WsServer WsServer(IUnityContainer c)
        {
            var httpServer = c.Resolve <HttpServer>();
            var server     = new WsServer(httpServer, "/Testing");

            server.ClientConnected += ServerOnClientConnected;

            return(server);
        }
Example #9
0
        private static async Task MainAsync(Settings settings)
        {
            DbClient.Init(settings.DbUri);
            Channels.WriteTimeout = 200;
            var server = new WsServer(settings.Port, WsHandler.ProcessWsConnectionAsync);
            await server.StartAsync().ConfigureAwait(false);

            Thread.Sleep(Timeout.Infinite);
        }
Example #10
0
 public BridgeSession(WsServer server,
                      ILogger <BridgeServer> logger,
                      IMediator mediator,
                      IEventMapper eventMapper) : base(server)
 {
     _logger      = logger;
     _mediator    = mediator;
     _eventMapper = eventMapper;
 }
Example #11
0
    async void IWsServerCallback.OnConnect(WsServer _, WsSocket socket)
    {
        Debug.Log($"Open: {socket.Address}");
        await socket.SendAsync("Hello world!");

        await socket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure);

        Debug.Log($"Close: {socket.Address}");
    }
Example #12
0
        public async Task Test()
        {
            // create the server
            var server    = new WsServer();
            var serverKey = CryptoExtensions.GenerateKey();
            var clientKey = CryptoExtensions.GenerateKey();

            Console.WriteLine($"Server key is: [{serverKey.Q.GetFingerprintString()}]");
            Console.WriteLine($"Client key is: [{clientKey.Q.GetFingerprintString()}]");
            await server.StartAsync(new IPEndPoint(IPAddress.Any, 8080), async stream =>
            {
                // encrypt
                // called when a client connects
                var br = new BinaryWriter(stream);
                var ct = Encoding.ASCII.GetBytes($"Hello from Server! {DateTime.Now}");
                br.Write(ct.Length);
                br.Write(ct);
                var res = await stream.EncryptAsync(serverKey);
                Console.WriteLine($"Client connected with fingerprint of [{res.GetFingerprintString()}]");
                while (stream.Connected)
                {
                    var bytes = Encoding.ASCII.GetBytes($"Hello from Server! {DateTime.Now}");
                    br.Write(bytes.Length);
                    br.Write(bytes);
                    await Task.Delay(1000);
                }
                await stream.CloseAsync();
            });

            // start client
            var client     = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));

            // measure client data

            // read data
            var binReader = new BinaryReader(connection);
            int e         = binReader.ReadInt32();
            var g         = binReader.ReadBytes(e);

            Console.WriteLine(Encoding.ASCII.GetString(g));

            var serverRes = await connection.EncryptAsync(clientKey);

            Console.WriteLine($"Connected to server with fingerprint of [{serverRes.GetFingerprintString()}]");

            for (int i = 0; i < 100; i++)
            {
                int b         = binReader.ReadInt32();
                var bytesRead = binReader.ReadBytes(b);
                Console.WriteLine(Encoding.ASCII.GetString(bytesRead));
            }
            // cleanup
            client.Dispose();
            server.Dispose();
        }
Example #13
0
    System.Collections.IEnumerator Start()
    {
        Debug.Log("Server Start");
        m_Server = new WsServer(WsServerOption.Default, this);
        m_Server.Start();

        yield return(new WaitForSeconds(10f));

        Destroy(this);
    }
Example #14
0
 protected virtual void Update()
 {
     // Send data
     WsServer.BroadcastPacket(new WidgetElementUpdatePacket()
     {
         WidgetId  = Widget.WidgetId,
         ElementId = ElementId,
         Data      = this
     });
 }
Example #15
0
        public MainHandler()
        {
            _config = BuildConfiguration();
            Singleton.Add <Configuration>(_config);
            Singleton.Add <HttpHandler>();
            Singleton.Add <CacheHandler>();
            Singleton.Add <SourceHandler>();
            Singleton.Add <WsServer>();

            _httpHandler = Singleton.Of <HttpHandler>();
            _wSServer    = Singleton.Of <WsServer>();
        }
Example #16
0
        public async Task Test()
        {
            // create the server
            var server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Loopback, 8080), async stream =>
            {
                //await stream.EncryptAsync();
                Console.WriteLine($"Tunnel Opened: remote => localhost:12345");
                var sock = new Socket(SocketType.Stream, ProtocolType.Tcp);
                await sock.ConnectAsync("localhost", 12345);
                var ns = new NetworkStream(sock);
                var t1 = ns.CopyToAsync(stream, 62000);
                var t2 = stream.CopyToAsync(ns, 62000);
                await Task.WhenAny(t1, t2);
                sock.Dispose();
                await stream.DisposeAsync();
                Console.WriteLine($"Tunnel Closed: remote => localhost:25565");
            });

            Socket lSock = new Socket(SocketType.Stream, ProtocolType.Tcp);

            lSock.Bind(new IPEndPoint(IPAddress.Loopback, 1234));
            lSock.Listen(10);
            var cts = new CancellationTokenSource();

            Console.WriteLine($"Started... Listening to localhost:1234. Press ctrl + c to exit");
            Console.CancelKeyPress += (q, e) =>
            {
                cts.Cancel();
            };
            while (!cts.Token.IsCancellationRequested)
            {
                var ksock = await lSock.AcceptAsync();

                Task.Run(async() =>
                {
                    // start client
                    var client     = new WsClient();
                    var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));
                    //await connection.EncryptAsync();
                    var ns = new NetworkStream(ksock);
                    var t1 = ns.CopyToAsync(connection, 62000);
                    var t2 = connection.CopyToAsync(ns, 62000);
                    await Task.WhenAny(t1, t2);
                    ksock.Dispose();
                    await connection.DisposeAsync();
                    client.Dispose();
                });
            }
            // cleanup
            server.Dispose();
        }
Example #17
0
 private void MapOnOnTileUpdated(object sender, TileUpdateEventArgs e)
 {
     WsServer.BroadcastTileUpdate(new TileUpdatePacket()
     {
         LayerId = e.LevelId + "_" + e.LayerId,
         Tile    = new Tile()
         {
             X    = e.TileX,
             Y    = e.TileY,
             Zoom = e.TileZoom
         }
     });
 }
Example #18
0
        private static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, args) => Console.Error.WriteLine(args.ExceptionObject);

            ThreadPool.SetMinThreads(HttpServerSettings.Concurrency, HttpServerSettings.Concurrency);
            ThreadPool.SetMaxThreads(HttpServerSettings.Concurrency, HttpServerSettings.Concurrency);

            var cancellation = new CancellationTokenSource();
            var token        = cancellation.Token;

            var wsServer = new WsServer <User>(9999, ws => Users.Find(ws.HttpRequest.Cookies?.GetAuth()));

            var authHandler = new AuthHandler(login => Task.Run(() => wsServer.BroadcastAsync(user => AuthHandler.FormatUserMessage(user, login), token), token));
            var foodHandler = new FoodHandler((login, food) => Task.Run(() => wsServer.BroadcastAsync(user => FoodHandler.FormatUserMessage(user, login, food), token), token));

            var staticHandler = new StaticHandler("static", ctx =>
            {
                var url = ctx.Request.Url;
                if (url.HostNameType != UriHostNameType.Dns && url.HostNameType != UriHostNameType.IPv4 && url.HostNameType == UriHostNameType.IPv6)
                {
                    throw new HttpException(400, "Invalid host");
                }

                ctx.Response.Headers["X-Frame-Options"]         = "deny";
                ctx.Response.Headers["X-XSS-Protection"]        = "1; mode=block";
                ctx.Response.Headers["Content-Security-Policy"] = $"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self' ws://{url.Host}:9999;";

                ctx.SetCsrfTokenCookie();
            });

            var httpServer = new HttpServer(8888)
                             .AddHandler("POST", "/signin", authHandler.SignInAsync)
                             .AddHandler("POST", "/signup", authHandler.SignUpAsync)
                             .AddHandler("POST", "/put", foodHandler.PutAsync)
                             .AddHandler("GET", "/get", foodHandler.GetAsync)
                             .AddHandler("GET", "/", staticHandler.GetAsync);

            Console.CancelKeyPress += (sender, args) =>
            {
                Console.Error.WriteLine("Stopping...");
                args.Cancel = true;
                cancellation.Cancel();
            };

            Task.WaitAll(wsServer.AcceptLoopAsync(token), httpServer.AcceptLoopAsync(token));
        }
Example #19
0
        /// <summary>
        /// Manager of server
        /// </summary>
        /// <param name = "webAddress">Web IP and Port</param>
        /// <param name = "tcpAddress">Tcp IP and Port</param>
        /// <param name = "timeout">Seconds life of client</param>
        /// <param name = "dataBaseManager">Base manager</param>
        public NetworkManager(IPEndPoint webAddress, IPEndPoint tcpAddress, int timeout, DataBaseManager dataBaseManager)
        {
            _dataBaseManager = dataBaseManager;

            _wsServer  = new WsServer(webAddress, timeout);
            _tcpServer = new TcpServer(tcpAddress, timeout);
            foreach (User user in _dataBaseManager.UserList)
            {
                _wsServer.UserOfflineList.Add(user.Name);
                _tcpServer.UserOfflineList.Add(user.Name);
            }

            _wsServer.ConnectionStateChanged += HandleConnectionStateChanged;
            _wsServer.MessageReceived        += HandleMessageReceived;

            _tcpServer.ConnectionStateChanged += HandleConnectionStateChanged;
            _tcpServer.MessageReceived        += HandleMessageReceived;
        }
Example #20
0
        public IntegrityTestFixture()
        {
            // create the server
            var server = new WsServer();

            server.StartAsync(new IPEndPoint(IPAddress.Loopback, 0), async stream =>
            {
                Server = stream;
            }).GetAwaiter().GetResult();

            // start client
            var client = new WsClient();

            Client = client.ConnectAsync(new Uri("ws://" + server.ListeningAddresses[0].Substring(7))).GetAwaiter().GetResult();
            Thread.Sleep(1000);
            Reader = new AsyncBinaryReader(Client);
            Writer = new AsyncBinaryWriter(Server);
        }
Example #21
0
        public async Task ValidateReadWriteStatistics()
        {
            InterceptData clientData = null, serverData = null;
            var           server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Loopback, 0), async stream =>
            {
                await stream.WrapSocketAsync(x =>
                                             Task.FromResult <WStreamSocket>(new Interceptor(x, out serverData))
                                             );
                var abr = new AsyncBinaryReader(stream);
                for (int i = 0; i < 100000; i++)
                {
                    Assert.Equal(i, await abr.ReadInt32Async());
                }
                await stream.CloseAsync();
            });

            var client     = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://" + server.ListeningAddresses[0].Substring(7)));

            await connection.WrapSocketAsync(x =>
                                             Task.FromResult <WStreamSocket>(new Interceptor(x, out clientData))
                                             );

            var abw = new AsyncBinaryWriter(connection);

            for (int i = 0; i < 100000; i++)
            {
                await abw.WriteAsync(i);
            }

            await abw.FlushAsync();

            await Task.Delay(1000);

            Assert.Equal(4 * 100000, clientData.BytesWritten);
            Assert.Equal(4 * 100000, serverData.BytesRead);

            client.Dispose();
            server.Dispose();
        }
Example #22
0
        public void Start()
        {
            if (!TryStartListener())
            {
                if (!TryAddUrlReservations())
                {
                    Log.ErrorFormat("Unable to add url reservations for web server.");
                    return;
                }

                if (!TryStartListener())
                {
                    Log.ErrorFormat("Unable to start listener");
                    return;
                }
            }

            WsServer.Start();
            _proxy.Start();
            Log.InfoFormat("Web server started.");
        }
Example #23
0
 public WebSocketServer(
     string ipAddress = "127.0.0.1",
     int port         = 8080,
     Action <WsSession, string> messageConsumerMethod = null,
     ILogger logger = null
     )
 {
     _ipAddress                     = ipAddress;
     _port                          = port;
     _messageConsumer               = messageConsumerMethod;
     _logger                        = logger;
     _server                        = new WsServer(IPAddress.Parse(ipAddress), port);
     _server.OnServerStarted       += OnWsServerStarted;
     _server.OnServerStopped       += OnWsServerStopped;
     _server.OnServerError         += OnWsServerError;
     _server.OnSessionError        += OnWsSessionError;
     _server.OnSessionConnected    += OnWsSessionConnected;
     _server.OnSessionDisconnected += OnWsSessionDisconnected;
     _server.OnMessageReceived     += OnWsMessageReceived;
     _server.OnEmptyMessage        += OnEmptyMessage;
     _server.OnMessageSent         += OnMessageSent;
 }
Example #24
0
        public async Task Test()
        {
            InterceptData clientData = null, serverData = null;
            // create the server
            var server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Any, 8080), async stream =>
            {
                // measure server data
                await stream.WrapSocketAsync(x =>
                                             // create a new interceptor
                                             Task.FromResult <WStreamSocket>(new Interceptor(x, out serverData))
                                             );
                // called when a client connects
                await stream.WriteAsync(BitConverter.GetBytes(DateTime.Now.ToBinary()));
                await stream.CloseAsync();
            });

            // start client
            var client = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));

            // measure client data
            await connection.WrapSocketAsync(x =>
                                             // create a new interceptor
                                             Task.FromResult <WStreamSocket>(new Interceptor(x, out clientData))
                                             );

            // read data
            var binReader = new BinaryReader(connection);

            Console.WriteLine($"Current time is {DateTime.FromBinary(binReader.ReadInt64())}");

            Console.WriteLine($"Intercepted Data from client - Written {clientData.BytesWritten} / Read {clientData.BytesRead}");
            Console.WriteLine($"Intercepted Data from server - Written {serverData.BytesWritten} / Read {serverData.BytesRead}");

            // cleanup
            client.Dispose();
            server.Dispose();
        }
Example #25
0
        public async Task Test()
        {
            // create the server
            var server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Any, 8080), async stream =>
            {
                // called when a client connects
                await stream.WriteAsync(BitConverter.GetBytes(DateTime.Now.ToBinary()));
                await stream.CloseAsync();
            });

            // start client
            var client     = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));

            // read data
            var binReader = new BinaryReader(connection);

            Console.WriteLine($"Current time is {DateTime.FromBinary(binReader.ReadInt64())}");

            // cleanup
            client.Dispose();
            server.Dispose();
        }
Example #26
0
        public NetworkManager()
        {
            ServerConfiguration configuration = new ServerConfiguration("configuration.xml");

            _transport        = configuration.Transport;
            _ip               = configuration.Ip;
            _port             = configuration.Port;
            _connectionString = configuration.ConnectionSettings;

            DatabaseHandler dbHandler = new DatabaseHandler(_connectionString);

            switch (_transport)
            {
            case 0:
            {
                _wsServer = new WsServer(new IPEndPoint(_ip, _port));
                _wsServer.ConnectionStateChanged += OnConnectionStateChanged;
                _wsServer.ConnectionReceived     += OnConnectionReceived;
                _wsServer.MessageReceived        += OnMessageReceived;
                _wsServer.ErrorReceived          += OnErrorReceived;
                _wsServer.FiltrationReceived     += OnFiltrationReceived;
                _wsServer.GroupCreated           += OnGroupCreated;
                _wsServer.GroupLeaved            += OnGroupLeaved;

                break;
            }

            default:
            {
                Console.WriteLine("Unexpected error");
                break;
            }
            }

            _requestHander = new RequestHandler(dbHandler);
        }
Example #27
0
        public async Task Test()
        {
            // create the server
            var server = new WsServer();
            await server.StartAsync(new IPEndPoint(IPAddress.Any, 8080), async stream =>
            {
                // called when a client connects
                var br = new BinaryWriter(stream);
                while (stream.Connected)
                {
                    var bytes = Encoding.ASCII.GetBytes($"Hello from Server! {DateTime.Now}");
                    br.Write(bytes.Length);
                    br.Write(bytes);
                    await Task.Delay(1000);
                }
                await stream.CloseAsync();
            });

            // start client
            var client     = new WsClient();
            var connection = await client.ConnectAsync(new Uri("ws://localhost:8080"));

            // read data
            var binReader = new BinaryReader(connection);

            for (int i = 0; i < 100; i++)
            {
                int b         = binReader.ReadInt32();
                var bytesRead = binReader.ReadBytes(b);
                Console.WriteLine(Encoding.ASCII.GetString(bytesRead));
            }

            // cleanup
            client.Dispose();
            server.Dispose();
        }
Example #28
0
 public MulticastSession(WsServer server) : base(server) { }
Example #29
0
 void IWsServerCallback.OnError(WsServer _, System.Exception exception)
 {
     Debug.LogException(exception);
 }
Example #30
0
 public ChatSession(WsServer server) : base(server)
 {
 }