Beispiel #1
1
        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            var config = new ServerConfig {
                Name = "SuperWebSocket",
                Ip = "Any",
                Port = 2012,
                Mode = SocketMode.Tcp,
            };

            Console.WriteLine("Starting WebSocketServer on port " + config.Port + "...");

            var socketServer = new WebSocketServer();
            socketServer.Setup(new RootConfig(), config);

            socketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(socketServer_NewMessageReceived);
            socketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(socketServer_NewSessionConnected);
            socketServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(socketServer_SessionClosed);

            if (!socketServer.Start()) {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press 'q' key to stop it!");

            while (Console.ReadKey().KeyChar != 'q') {
                Console.WriteLine();
                continue;
            }
            socketServer.Stop();

            Console.WriteLine("\nThe server stopped!");
        }
Beispiel #3
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //-- 启动一个服务器
            appServer = new AppServer();

            var serverConfig = new ServerConfig
            {
                Port = 2010, //set the listening port
                TextEncoding = "UTF-8",
            };

            //Setup the appServer
            if (!appServer.Setup(serverConfig))
            {
                System.Diagnostics.Debug.Write("创建App Server失败");
            }

            //Try to start the appServer
            if (!appServer.Start())
            {
                System.Diagnostics.Debug.Write("启动App Server失败");
            }

            var mainFrm = new MainForm();
            appServer.NewSessionConnected += mainFrm.appServerNewSessionConnected;
            appServer.SessionClosed += mainFrm.appServerSessionClosed;
            Application.Run(mainFrm);

            //Stop the appServer
            appServer.Stop();
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            //int port = int.Parse(args[0]);
            int port = 443;
            ServerConfig serverConfig = new ServerConfig
            {
                Name = "SecureSuperWebSocket",
                Ip = "Any",
                Port = port,
                MaxRequestLength = 10485760,
                SendingQueueSize = 500,
                ReceiveBufferSize = 2050 * 1024,
                //SendBufferSize = 600 * 1024,
            };

            socketServer = new WebSocketServer();
            socketServer.NewSessionConnected += SocketServer_NewSessionConnected;
            socketServer.NewDataReceived += SocketServer_NewDataReceived;
            //socketServer.NewMessageReceived += SocketServer_NewMessageReceived;
            socketServer.Setup(serverConfig);
            socketServer.Start();

            Console.WriteLine("Server is running on port {0} ...", port);

            Console.ReadKey();
        }
        public async void Init()
        {
            Logger.Info("Initing...");
            var config = new ServerConfig
                {
                    Port = _settings.ServerPort,
                    Ip = "Any", 
                    MaxConnectionNumber = 2000,
                    Mode = SocketMode.Tcp,
                    //ReceiveBufferSize = 1024,
                    //SendBufferSize = 1024,
                    Name = "AboSocketServer",
                    DisableSessionSnapshot = true,
                    LogAllSocketException = false,
                    LogBasicSessionActivity = false,
                    LogCommand = false, 
                    //LogFactory = "DefaultLogFactory"
                };

            var setuped = _aboSocketServer.Setup(config);
            var started = _aboSocketServer.Start();
            Database.SetInitializer(new DropCreateDatabaseAlways<UnitOfWork>());
            //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<UnitOfWork>());
            Logger.Info("Init completed {0}({1})", setuped, started);
        }
        public void TestCopyProperties()
        {
            var config = new ServerConfig();
            config.Name = "Kerry";
            config.Port = 21;
            var newConfig = new ServerConfig();
            config.CopyPropertiesTo(newConfig);

            Assert.AreEqual(config.Name, newConfig.Name);
            Assert.AreEqual(config.Port, newConfig.Port);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the server!");

            Console.ReadKey();
            Console.WriteLine();

            var appServer = new AppServer();

            //Setup with config model, which provides more options
            var serverConfig = new ServerConfig
            {
                Port = 2012, //set the listening port
                //Other configuration options
                //Mode = SocketMode.Udp,
                //MaxConnectionNumber = 100,
                //...
            };

            //Setup the appServer
            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }

            appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);

            Console.WriteLine();

            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }

            Console.WriteLine();
            //Stop the appServer
            appServer.Stop();
            
            Console.WriteLine("The server was stopped!");
        }
Beispiel #8
0
        private IServerConfig ResolveServerConfig(IServerConfig serverConfig)
        {
            var config = new ServerConfig();
            serverConfig.CopyPropertiesTo(config);

            if (serverConfig.Port > 0)
            {
                var endPointKey = serverConfig.Name + "_" + serverConfig.Port;
                var instanceEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endPointKey];
                if (instanceEndpoint == null)
                {
                    Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey), "Error");
                    return serverConfig;
                }

                var ipEndpoint = instanceEndpoint.IPEndpoint;
                config.Ip = ipEndpoint.Address.ToString();
                config.Port = ipEndpoint.Port;
            }

            if (config.Listeners != null && config.Listeners.Any())
            {
                var listeners = config.Listeners.ToArray();

                var newListeners = new List<ListenerConfig>(listeners.Length);

                for (var i = 0; i < listeners.Length; i++)
                {
                    var listener = listeners[i];

                    var endPointKey = serverConfig.Name + "_" + listener.Port;
                    var instanceEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endPointKey];
                    if (instanceEndpoint == null)
                    {
                        Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey), "Error");
                        return serverConfig;
                    }

                    var newListener = new ListenerConfig();
                    newListener.Ip = instanceEndpoint.IPEndpoint.Address.ToString();
                    newListener.Port = instanceEndpoint.IPEndpoint.Port;
                    newListener.Backlog = listener.Backlog;

                    newListeners.Add(newListener);
                }

                config.Listeners = newListeners;
            }

            return config;
        }
        public void TestECHO()
        {
            IServerConfig config = new ServerConfig
            {
                Name = "My Custom Server",
                Ip = "Any",
                Port = 100,
                Mode = SocketMode.Async,
                MaxConnectionNumber = 1
            };

            var rootConfig = new RootConfig
            {
                LoggingMode = LoggingMode.Console
            };

            YourServer server = new YourServer();
            server.Setup(rootConfig, config, SocketServerFactory.Instance);

            server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);
                Stream socketStream = new NetworkStream(socket);
                using (StreamReader reader = new StreamReader(socketStream, Encoding.Default, true))
                using (StreamWriter writer = new StreamWriter(socketStream, Encoding.Default, 1024 * 8))
                {
                    //ignore welcome message
                    reader.ReadLine();

                    string command = "CMD:ECHO ";
                    string[] parameters = new string[] { "Kerry", "Jiang", "China", "Shanghai" };
                    string parameter = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Join(" ", parameters)));
                    writer.WriteLine(command + parameter);
                    writer.Flush();

                    foreach (var p in parameters)
                    {
                        string param = reader.ReadLine();
                        Console.WriteLine(param);
                        Assert.AreEqual(p, param);
                    }
                }
            }

            server.Stop();
        }
 public bool Start()
 {
     var config = new ServerConfig
     {
         Port = port,
         Ip = ip,
         Mode = SocketMode.Tcp,
         Name = "CommandServer"
     };
     Server = new CommandServer();
     if (Server.Setup(config))
         return Server.Start();
     else return false;
 }
Beispiel #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the server!");

            Console.ReadKey();
            Console.WriteLine();

            var appServer = new TelnetServer();

            var serverConfig = new ServerConfig
            {
                Port = 2012 //set the listening port
            };

            //Setup the appServer
            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine();

            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }

            Console.WriteLine();

            //Stop the appServer
            appServer.Stop();

            Console.WriteLine();
            Console.WriteLine("The server was stopped!");
            Console.ReadKey();
        }
        protected void Setup(WebSocketServer websocketServer, Action<ServerConfig> configurator)
        {
            var rootConfig = new RootConfig { DisablePerformanceDataCollector = true };
            websocketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(m_WebSocketServer_NewSessionConnected);
            websocketServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(m_WebSocketServer_SessionClosed);

            var config = new ServerConfig();
            configurator(config);

            var ret = websocketServer.Setup(rootConfig, config, null, null, new ConsoleLogFactory(), null, null);

            Assert.IsTrue(ret);

            m_WebSocketServer = websocketServer;
        }
        private IServerConfig ResolveServerConfig(IServerConfig serverConfig)
        {
            var config = new ServerConfig();
            serverConfig.CopyPropertiesTo(config);

            var instanceEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[serverConfig.Name + "Endpoint"];
            if (instanceEndpoint == null)
            {
                Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", serverConfig.Name + "Endpoint"), "Error");
                return serverConfig;
            }

            var ipEndpoint = instanceEndpoint.IPEndpoint;
            config.Ip = ipEndpoint.Address.ToString();
            config.Port = ipEndpoint.Port;
            return config;
        }
        private TestServer CreateServer(IReceiveFilterFactory<StringPackageInfo> receiveFilterFactory, SocketMode mode)
        {
            var appServer = new TestServer();

            var serverConfig = new ServerConfig();
            serverConfig.Ip = "127.0.0.1";
            serverConfig.Port = 2012;
            serverConfig.Mode = mode;
            serverConfig.MaxRequestLength = 40960;
            serverConfig.DisableSessionSnapshot = true;

            var setupResult = appServer.Setup(serverConfig, receiveFilterFactory, new ConsoleLoggerFactory(), null, null);

            Assert.IsTrue(setupResult);
            Assert.IsTrue(appServer.Start());

            return appServer;
        }
Beispiel #15
0
 /// <summary>
 /// 启动服务
 /// </summary>
 /// <returns></returns>
 public void Start()
 {
     var serConfig = new ServerConfig();
     serConfig.Port = _port;
     serConfig.Ip = _ip;
     //设置编码类型,默认的我试过了,Unity3D无法识别中文
     serConfig.TextEncoding = "GB2312";
     if (!app.Setup(serConfig))
     {
         Console.WriteLine("ChatWebSocket 设置WebSocket服务侦听地址失败");
         return;
     }
     if (!app.Start())
     {
         Console.WriteLine("ChatWebSocket 启动WebSocket服务侦听失败");
         return;
     }
     Console.WriteLine("ChatWebSocket 启动服务成功");
 }
Beispiel #16
0
        public WebSocketInterface(int port, Session session)
        {
            _session = session;
            var translations = session.Translation;
            _server = new WebSocketServer();
            _websocketHandler = WebSocketEventManager.CreateInstance();
            var config = new ServerConfig
            {
                Name = "NecroWebSocket",
                Mode = SocketMode.Tcp,
                Certificate = new CertificateConfig
                {
                    FilePath = @"cert.pfx",
                    Password = "******"
                },
            };
            config.Listeners = new List<ListenerConfig>
            {
                new ListenerConfig()
                {
                    Ip = "Any", Port = port, Security = "tls"
                },
                new ListenerConfig()
                {
                    Ip = "Any", Port = port + 1, Security = "none"
                }
            };

            var setupComplete = _server.Setup(config);

            if (setupComplete == false)
            {
                Logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, port), LogLevel.Error);
                return;
            }

            _server.NewMessageReceived += HandleMessage;
            _server.NewSessionConnected += HandleSession;

            _server.Start();
        }
Beispiel #17
0
        protected override void OnConfigure(IServerConfig config)
        {
            AppServer = new GatewayAppServer();
            int port = int.Parse(config.Options["port"]);
            var serverConfig = new SuperSocket.SocketBase.Config.ServerConfig()
            {
                Ip = "Any",
                Port = port,
                KeepAliveTime = 10,
                DisableSessionSnapshot = true,
                SendTimeOut = 0,
                MaxConnectionNumber = 3000
            };
            serverConfig.OptionElements = config.OptionElements;
            serverConfig.Options = config.Options;

            if (!AppServer.Setup(new RootConfig(), serverConfig))
            {
                throw new Exception("setup failed");
            }
        }
Beispiel #18
0
        protected override void OnConfigure(IServerConfig config)
        {
            AppServer = new GatewayAppServer();
            int port         = int.Parse(config.Options["port"]);
            var serverConfig = new SuperSocket.SocketBase.Config.ServerConfig()
            {
                Ip                     = "Any",
                Port                   = port,
                KeepAliveTime          = 10,
                DisableSessionSnapshot = true,
                SendTimeOut            = 0,
                MaxConnectionNumber    = 3000
            };

            serverConfig.OptionElements = config.OptionElements;
            serverConfig.Options        = config.Options;

            if (!AppServer.Setup(new RootConfig(), serverConfig))
            {
                throw new Exception("setup failed");
            }
        }
        public async void Init()
        {
            Logger.Info("Initing...");
            var config = new ServerConfig
                {
                    Port = _settings.ServerPort,
                    Ip = "Any", 
                    MaxConnectionNumber = 2000,
                    Mode = SocketMode.Tcp,
                    Name = "CrosschatSocketServer",
                    DisableSessionSnapshot = true,
                    LogAllSocketException = false,
                    LogBasicSessionActivity = false,
                    LogCommand = false, 
                };

            var setuped = _crosschatSocketServer.Setup(config);
            var started = _crosschatSocketServer.Start();
            //Database.SetInitializer(new DropCreateDatabaseAlways<UnitOfWork>());
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<UnitOfWork>());
            var user = new UnitOfWork().Users.FirstOrDefault();
            Logger.Info("Init completed {0}({1})", setuped, started);
        }
        public ITransportListener StartConnectionListener(string uri, int port)
        {
            ServerConfig config = new ServerConfig();
            config.Port = port;
            config.MaxRequestLength = 100000;

            string host = uri;
            if (host != "Any")
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(host);
                if (ipAddresses.Length == 0)
                    throw new Error(ErrorCode.CONNECTION_ERROR, "Cannot identify IP address by hostname.");
                config.Ip = ipAddresses[0].ToString();  // we take first entry as it does not matter which one is used
            }
            else
            {
                config.Ip = "Any";
            }
            var server = new WSServer();
            server.Setup(config);
            server.Start();
            return server as ITransportListener;
        }
        static void Main(string[] args)
        {
            ServerConfig serverConfig = new ServerConfig
            {
                Name = "SecureSuperWebSocket",
                Ip = "Any",
                Port = 9999,
                MaxRequestLength = 10485760,
                SendingQueueSize = 500,
                ReceiveBufferSize = 600 * 1024,
                SendBufferSize = 600 * 1024,
            };

            WebSocketServer socketServer = new WebSocketServer();
            socketServer.NewSessionConnected += SocketServer_NewSessionConnected;
            socketServer.NewDataReceived += SocketServer_NewDataReceived;
            socketServer.Setup(serverConfig);
            socketServer.Start();

            Console.WriteLine("Server is running on port 9999 ...");

            Console.ReadKey();
        }
        protected override void OnStart(string[] args)
        {
            string value = System.Configuration.ConfigurationManager.AppSettings["Port"];
            int port = SysUtils.ToInt(value);
            if (port <= 0)
                port = 2012;

            m_WebSocketServer = new WebSocketServer();
            var rootConfig = new RootConfig { DisablePerformanceDataCollector = true };

            m_WebSocketServer.NewDataReceived += m_WebSocketServer_NewDataReceived;
            m_WebSocketServer.NewMessageReceived += m_WebSocketServer_NewMessageReceived;
            m_WebSocketServer.NewSessionConnected += m_WebSocketServer_NewSessionConnected;
            m_WebSocketServer.SessionClosed += m_WebSocketServer_SessionClosed;

            var config = new ServerConfig();
            config.Port = port;
            config.Ip = "Any";
            config.MaxConnectionNumber = 100;
            config.MaxRequestLength = 100000;
            config.Name = "WebSocket Proxy Server";
            var ret = m_WebSocketServer.Setup(rootConfig, config, null, null, new ConsoleLogFactory(), null, null);
            m_WebSocketServer.Start();

            _container = ComponentManager.GetInstance();
            IHandler[] handlers = _container.Kernel.GetHandlers(typeof(IDeviceService));
            devicelist = new List<IDeviceService>();
            IDeviceService deviceservice;
            foreach (IHandler handler in handlers)
            {
                deviceservice = (IDeviceService)_container[handler.ComponentModel.Name];
                deviceservice.webSocketServer = m_WebSocketServer;
                devicelist.Add(deviceservice);
            }

            _logger.Info(string.Format("启动成功,port={0}", port));
        }
        private IServerConfig ResolveServerConfig(IServerConfig serverConfig)
        {
            var config = new ServerConfig();
            serverConfig.CopyPropertiesTo(config);

            RoleInstanceEndpoint instanceEndpoint;
            if (!RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.TryGetValue(serverConfig.Name + "Endpoint", out instanceEndpoint))
            {
                Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", serverConfig.Name + "Endpoint"), "Error");
                return serverConfig;
            }

            var ipEndpoint = instanceEndpoint.IPEndpoint;
            config.Ip = ipEndpoint.Address.ToString();
            config.Port = ipEndpoint.Port;

            List<int> dataPorts = new List<int>();

            int dataPortIndex = 0;

            while (true)
            {
                var dataPortKey = "FTPDataPort" + dataPortIndex++;

                RoleInstanceEndpoint dataEndpoint;
                if (!RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.TryGetValue(dataPortKey, out dataEndpoint))
                    break;

                dataPorts.Add(dataEndpoint.IPEndpoint.Port);
            }

            if (dataPorts.Count > 0)
                config.Options["dataPort"] = string.Join(",", dataPorts.Select(p => p.ToString()).ToArray());

            return config;
        }
        private TestServer CreateServer(IReceiveFilterFactory<StringRequestInfo> receiveFilterFactory)
        {
            var appServer = new TestServer();

            var serverConfig = new ServerConfig();
            serverConfig.Ip = "127.0.0.1";
            serverConfig.Port = 2012;

            var setupResult = appServer.Setup(serverConfig, null, receiveFilterFactory, new ConsoleLogFactory(), null, null);

            Assert.IsTrue(setupResult);
            Assert.IsTrue(appServer.Start());

            return appServer;
        }
        private bool TestMaxConnectionNumber(int maxConnectionNumber)
        {
            var server = new TestServer();
            var defaultConfig = DefaultServerConfig;

            var config = new ServerConfig
            {
                Ip = defaultConfig.Ip,
                LogCommand = defaultConfig.LogCommand,
                MaxConnectionNumber = maxConnectionNumber,
                Mode = defaultConfig.Mode,
                Name = defaultConfig.Name,
                Port = defaultConfig.Port,
                Security = defaultConfig.Security,
                Certificate = defaultConfig.Certificate
            };

            server.Setup(m_RootConfig, config, SocketServerFactory.Instance);

            List<Socket> sockets = new List<Socket>();

            try
            {
                server.Start();

                EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

                for (int i = 0; i < maxConnectionNumber; i++)
                {
                    Socket socket = CreateClientSocket();
                    socket.Connect(serverAddress);
                    Stream socketStream = GetSocketStream(socket);
                    StreamReader reader = new StreamReader(socketStream, m_Encoding, true);
                    reader.ReadLine();
                    sockets.Add(socket);
                }

                try
                {
                    using (Socket trySocket = CreateClientSocket())
                    {
                        trySocket.Connect(serverAddress);
                        var innerSocketStream = new NetworkStream(trySocket);
                        innerSocketStream.ReadTimeout = 500;

                        using (StreamReader tryReader = new StreamReader(innerSocketStream, m_Encoding, true))
                        {
                            string welcome = tryReader.ReadLine();
                            Console.WriteLine(welcome);
                            return true;
                        }
                    }
                }
                catch (Exception)
                {
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + " " + e.StackTrace);
                return false;
            }
            finally
            {
                server.Stop();
            }
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the WebSocketServer!");

            Console.ReadKey();
            Console.WriteLine();

            ks = KinectSensor.GetDefault();

            var fd = ks.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
            uint frameSize = fd.BytesPerPixel * fd.LengthInPixels;
            colorData.Data = new byte[frameSize];
            colorData.Format = ColorImageFormat.Bgra;

            msfr = ks.OpenMultiSourceFrameReader(FrameSourceTypes.Body | FrameSourceTypes.Color);

            msfr.MultiSourceFrameArrived += msfr_MultiSourceFrameArrived;

            bodies = new Body[ks.BodyFrameSource.BodyCount];
            ks.Open();

            appServer = new WebSocketServer();

            var config = new ServerConfig();
            config.Name = "kinect";
            config.Port = 2012;
            config.MaxRequestLength = (int)frameSize;

            // Setup the appServer
            if (!appServer.Setup(config)) //Setup with listening port
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine();

            // Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }

            //Stop the appServer
            appServer.Stop();

            Console.WriteLine();
            Console.WriteLine("The server was stopped!");
            Console.ReadKey();
        }
Beispiel #27
0
        private IServerConfig ReplaceListenEndPoint(IServerConfig serverConfig, IDictionary<string, IPEndPoint> listenEndPointReplacement)
        {
            var config = new ServerConfig(serverConfig);

            if (serverConfig.Port > 0)
            {
                var endPointKey = serverConfig.Name + "_" + serverConfig.Port;

                IPEndPoint instanceEndpoint;

                if(!listenEndPointReplacement.TryGetValue(endPointKey, out instanceEndpoint))
                {
                    throw new Exception(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey));
                }

                config.Ip = instanceEndpoint.Address.ToString();
                config.Port = instanceEndpoint.Port;
            }

            if (config.Listeners != null && config.Listeners.Any())
            {
                var listeners = config.Listeners.ToArray();

                for (var i = 0; i < listeners.Length; i++)
                {
                    var listener = (ListenerConfig)listeners[i];

                    var endPointKey = serverConfig.Name + "_" + listener.Port;

                    IPEndPoint instanceEndpoint;

                    if (!listenEndPointReplacement.TryGetValue(endPointKey, out instanceEndpoint))
                    {
                        throw new Exception(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey));
                    }

                    listener.Ip = instanceEndpoint.Address.ToString();
                    listener.Port = instanceEndpoint.Port;
                }

                config.Listeners = listeners;
            }

            return config;
        }
        private bool TestMaxConnectionNumber(int maxConnectionNumber)
        {
            var configSource = SetupBootstrap(DefaultServerConfig, new Func<IServerConfig, IServerConfig>(c =>
                {
                    var nc = new ServerConfig(c);
                    nc.MaxConnectionNumber = maxConnectionNumber;
                    return nc;
                }));

            BootStrap.Start();

            var config = configSource.Servers.FirstOrDefault();
            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), config.Port);

            List<Socket> sockets = new List<Socket>();

            var server = BootStrap.AppServers.FirstOrDefault();

            try
            {
                for (int i = 0; i < maxConnectionNumber; i++)
                {
                    Socket socket = CreateClientSocket();
                    socket.Connect(serverAddress);
                    Stream socketStream = GetSocketStream(socket);
                    StreamReader reader = new StreamReader(socketStream, m_Encoding, true);
                    reader.ReadLine();
                    sockets.Add(socket);
                }

                Assert.AreEqual(maxConnectionNumber, server.SessionCount);

                Assert.IsFalse(TryConnect(serverAddress));

                sockets[0].SafeClose();

                Thread.Sleep(500);

                Assert.AreEqual(maxConnectionNumber - 1, server.SessionCount);

                return TryConnect(serverAddress);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + " " + e.StackTrace);
                throw e;
            }
            finally
            {
                ClearBootstrap();
            }
        }
        private bool TestMaxConnectionNumber(int maxConnectionNumber)
        {
            var server = new TestServer();
            var defaultConfig = DefaultServerConfig;

            var config = new ServerConfig
            {
                Ip = defaultConfig.Ip,
                LogCommand = defaultConfig.LogCommand,
                MaxConnectionNumber = maxConnectionNumber,
                Mode = defaultConfig.Mode,
                Name = defaultConfig.Name,
                Port = defaultConfig.Port
            };

            ((ITestSetup)server).Setup(m_RootConfig, config);

            List<Socket> sockets = new List<Socket>();

            try
            {
                server.Start();

                EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

                for (int i = 0; i < maxConnectionNumber; i++)
                {
                    Socket socket = CreateClientSocket();
                    socket.SendTo(m_Encoding.GetBytes(Guid.NewGuid().ToString() + m_NewLine), serverAddress);
                    Console.WriteLine("C: " + m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()));
                    sockets.Add(socket);
                }

                using (Socket trySocket = CreateClientSocket())
                {
                    trySocket.SendTo(m_Encoding.GetBytes(Guid.NewGuid().ToString() + m_NewLine), serverAddress);
                    Thread thread = new Thread(new ThreadStart(() =>
                        {
                            Console.WriteLine("C: " + m_Encoding.GetString(ReceiveMessage(trySocket, serverAddress).ToArray()));
                        }));
                    thread.Start();
                    if (thread.Join(500))
                    {
                        //Assert.Fail("Current connection number: {0}, max connectionnumber: {1}", maxConnectionNumber + 1, maxConnectionNumber);
                        return false;
                    }
                    else
                    {
                        thread.Abort();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + " " + e.StackTrace);
                return false;
            }
            finally
            {
                server.Stop();
            }
        }