Exemplo n.º 1
0
        static void Main(string[] args)
        {
            #region 初始化Socket
            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();
            if (!bootstrap.Initialize())
            {
                Console.WriteLine(DateTime.Now + ":Socket初始化失败\r\n");
                return;
            } 
            var result = bootstrap.Start();
            foreach (var server in bootstrap.AppServers)
            {
                if (server.State == ServerState.Running)
                {
                    Console.WriteLine(DateTime.Now + ":serverName为:" + server.Name + "Socket运行中\r\n");
                    
                }
                else
                {
                    Console.WriteLine(DateTime.Now + ":serverName为:" + server.Name + "Socket启动失败\r\n");

                }
            }
            Console.ReadKey(); 
            #endregion
        }
Exemplo n.º 2
0
 public static bool Start()
 {
     try
     {
         var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LogServiceConfigFileName);
         IBootstrap = BootstrapFactory.CreateBootstrapFromConfigFile(configFilePath);
         if (!IBootstrap.Initialize())
         {
             Console.WriteLine("日志服务初始化失败");
             Logger.Error("日志服务启动失败!");
             return(false);
         }
         var result = IBootstrap.Start();
         if (result == StartResult.Failed)
         {
             Console.WriteLine("日志服务启动失败!");
             Logger.Error("日志服务启动失败!");
             return(false);
         }
         return(true);
     }
     catch (Exception ex)
     {
         Logger.Error($"启动日志Socket服务失败:{ex}");
         return(false);
     }
 }
Exemplo n.º 3
0
 protected override void OnStart(string[] args)
 {
     if (bootstrap.Initialize())
     {
         bootstrap.Start();
     }
 }
Exemplo n.º 4
0
        public void SetUp()
        {
            if (!bootstrap.Initialize())
            {
                Console.WriteLine("Failed to initialize!");
            }

            var result = bootstrap.Start();

            Console.WriteLine("Start result: {0}!", result);

            if (result == StartResult.Success)
            {
                client          = new PirateXClient("ps://localhost:3002");
                client.OnError += (sender, args) =>
                {
                    throw new Exception(args.ToString());
                };
                client.OnOpen += (sender, args) =>
                {
                    Console.WriteLine("Connect!");

                    Assert.IsTrue(true);
                };


                client.Open();
            }


            Thread.Sleep(3000);
        }
Exemplo n.º 5
0
 public void Setup()
 {
     m_Bootstrap = BootstrapFactory.CreateBootstrapFromConfigFile("SuperSocket.config");
     Assert.IsTrue(m_Bootstrap.Initialize());
     m_Port = ((IAppServer)m_Bootstrap.AppServers.FirstOrDefault()).Config.Port;
     Assert.AreEqual(StartResult.Success, m_Bootstrap.Start());
 }
Exemplo n.º 6
0
 private static log4net.ILog log = log4net.LogManager.GetLogger("SuperSocketMain");//log2.0.3->2.0.8
 public static void Init()
 {
     try
     {
         Console.WriteLine("Welcome to LotServer!");
         IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();
         if (!bootstrap.Initialize())
         {
             Console.WriteLine("LotServer初始化失败");
             Console.ReadKey();
             return;
         }
         Console.WriteLine("LotServer启动中...");
         var result = bootstrap.Start();
         foreach (var server in bootstrap.AppServers)
         {
             if (server.State == ServerState.Running)
             {
                 Console.WriteLine("- {0} 运行中", server.Name);
             }
             else
             {
                 Console.WriteLine("- {0} 启动失败", server.Name);
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     Console.Read();
 }
Exemplo n.º 7
0
 public void Setup()
 {
     m_Bootstrap = BootstrapFactory.CreateBootstrapFromConfigFile("SuperSocket.config");
     Assert.IsTrue(m_Bootstrap.Initialize());
     m_Port = ((IAppServer) m_Bootstrap.AppServers.FirstOrDefault()).Config.Port;
     Assert.AreEqual(StartResult.Success, m_Bootstrap.Start());
 }
Exemplo n.º 8
0
        public static void Init()
        {
            Console.WriteLine("Welcome to SuperSocket SocketService");
            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("初始化");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("启动中");
            var result = bootstrap.Start();

            foreach (var server in bootstrap.AppServers)
            {
                if (server.State == ServerState.Running)
                {
                    Console.WriteLine($"- {server.Name} 运行中");
                }
                else
                {
                    Console.WriteLine($"- {server.Name} 启动失败");
                }
            }
        }
Exemplo n.º 9
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            bootstrap.Stop();
            txtMsg.Items.Add("Server Has Stop ");
            //var bootstrap = BootstrapFactory.CreateBootstrap();
            //if (!bootstrap.Initialize())
            //{
            //    txtMsg.Items.Add("Failed to initialize!");
            //    //Console.ReadKey();
            //    return;
            //}
            //bootstrap.Stop()
            var result = bootstrap.Start();

            //TelnetServer sss = bootstrap.AppServers.First() as TelnetServer;
            //sss.NewSessionConnected += sss_NewSessionConnected;
            txtMsg.Items.Add(string.Format("Start result: {0}!", result));

            if (result == StartResult.Failed)
            {
                txtMsg.Items.Add("Failed to start!");
                // Console.ReadKey();
                return;
            }
        }
Exemplo n.º 10
0
        public static void Init()
        {
            try
            {
                //支持通过配置文件读取对服务启动
                IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();
                if (!bootstrap.Initialize())
                {
                    Console.WriteLine("初始化失败");
                    Console.ReadKey();
                    return;
                }
                Console.WriteLine("准备启动服务");
                var result = bootstrap.Start();

                foreach (var server in bootstrap.AppServers)
                {
                    if (server.State == ServerState.Running)
                    {
                        Console.WriteLine($"{server.Name}运行中");
                    }
                    else
                    {
                        Console.WriteLine($"{server.Name}启动失败");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
Exemplo n.º 11
0
        void StartSuperWebSocketByConfig()
        {
            m_Bootstrap = new DefaultBootstrap();

            var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig;

            if (!m_Bootstrap.Initialize(serverConfig))
            {
                return;
            }

            var socketServer       = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SuperWebSocket")) as WebSocketServer;
            var secureSocketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SecureSuperWebSocket")) as WebSocketServer;

            Application["WebSocketPort"]       = socketServer.Config.Port;
            Application["SecureWebSocketPort"] = secureSocketServer.Config.Port;

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

            secureSocketServer.NewSessionConnected += secureSocketServer_NewSessionConnected;
            secureSocketServer.SessionClosed       += secureSocketServer_SessionClosed;

            m_Bootstrap.Start();
        }
Exemplo n.º 12
0
        //窗体加载的时候开启监听
        private void Form1_Load(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo("Config/log4net.config"));
            //声明bootStrap实例
            bootstrap = BootstrapFactory.CreateBootstrap();
            //初始化
            if (!bootstrap.Initialize())
            {
                SetMessage("Failed to initialize!");
                return;
            }
            //开启服务
            var result = bootstrap.Start();

            if (result == StartResult.Failed)
            {
                SetMessage("Failed to start!");

                return;
            }
            else
            {
                SetMessage("服务器启动成功");
            }
        }
Exemplo n.º 13
0
        protected IConfigurationSource StartBootstrap(string configFile, Func <IServerConfig, IServerConfig> configResolver)
        {
            var configSource = SetupBootstrap(configFile, configResolver);
            var result       = m_BootStrap.Start();

            Assert.AreEqual(StartResult.Success, result);
            return(configSource);
        }
Exemplo n.º 14
0
 /// <summary>
 /// 启动服务
 /// </summary>
 /// <param name="args"></param>
 protected override void OnStart(string[] args)
 {
     if (!m_Bootstrap.Initialize())
     {
         return;
     }
     m_Bootstrap.Start();
 }
Exemplo n.º 15
0
        static void RunAsConsole()
        {
            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("Failed to initialize SuperSocket server! Please check error log for more information!");
                return;
            }

            var result = bootstrap.Start();

            foreach (var server in bootstrap.AppServers)
            {
                if (server.IsRunning)
                {
                    Console.WriteLine("- {0} has been started", server.Name);
                }
                else
                {
                    Console.WriteLine("- {0} failed to start", server.Name);
                }
            }

            switch (result)
            {
            case (StartResult.None):
                Console.WriteLine("No server is configured, please check you configuration!");
                break;

            case (StartResult.Success):
                Console.WriteLine("The server engine has been started!");
                break;

            case (StartResult.Failed):
                Console.WriteLine("Failed to start the server engine! Please check error log for more information!");
                break;

            case (StartResult.PartialSuccess):
                Console.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!");
                break;
            }

            Console.WriteLine("Press key 'q' to stop the server engine.");

            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                Console.WriteLine();
                continue;
            }

            bootstrap.Stop();

            Console.WriteLine();
            Console.WriteLine("The server engine has been stopped!");
        }
Exemplo n.º 16
0
        protected override void OnStart(string[] args)
        {
            var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig;

            if (!m_Bootstrap.Initialize(serverConfig))
            {
                return;
            }

            m_Bootstrap.Start();
        }
Exemplo n.º 17
0
 private void btnStartStop_Click(object sender, EventArgs e)
 {
     if (btnStartStop.Text == "启动服务")
     {
         bootstrap = BootstrapFactory.CreateBootstrap();
         if (!bootstrap.Initialize())
         {
             ServiceStatus = false;
             MessageBox.Show("Failed to initialize!");
             return;
         }
         else
         {
             StartResult result = bootstrap.Start();
             if (result == StartResult.Failed)
             {
                 ServiceStatus = false;
             }
             else if (result == StartResult.Success)
             {
                 var transferServer = bootstrap.GetServerByName("TransferServer") as TransferServer;
                 transferServer.NewSessionConnected += transferServer_NewSessionConnected;
                 transferServer.SessionClosed       += transferServer_SessionClosed;
                 var userServer = bootstrap.GetServerByName("UserServer") as UserServer;
                 userServer.UserJoin     += userServer_UserJoin;
                 userServer.UserLeave    += userServer_UserLeave;
                 userServer.SendToServer += userServer_UserSendToServer;
                 userServer.UserWhisper  += userServer_UserWhisper;
                 userServer.Broadcast    += userServer_UserBroadcast;
                 ServiceStatus            = true;
             }
             else
             {
                 //MessageBox.Show(string.Format("Start result: {0}!", result));
             }
             this.lblStatus.Text = result.ToString();
         }
     }
     else
     {
         bootstrap.Stop();
         ServiceStatus       = false;
         this.lblStatus.Text = "The server was stopped!";
     }
     if (ServiceStatus)
     {
         btnStartStop.Text = "停止服务";
     }
     else
     {
         btnStartStop.Text = "启动服务";
     }
 }
Exemplo n.º 18
0
        private IConfigurationSource SetupBootstrap(string configFile)
        {
            var configSource = CreateBootstrap(configFile);

            Assert.IsTrue(m_BootStrap.Initialize());

            var result = m_BootStrap.Start();

            Assert.AreEqual(StartResult.Success, result);

            return(configSource);
        }
Exemplo n.º 19
0
        static void RunAsConsole()
        {
            Console.WriteLine("Welcome to NRack.Server!");

            CheckCanSetConsoleColor();

            Console.WriteLine("Initializing...");

            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                SetConsoleColor(ConsoleColor.Red);

                Console.WriteLine("Failed to initialize NRack.Server! Please check error log for more information!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("Starting...");

            bootstrap.Start();

            Console.WriteLine("-------------------------------------------------------------------");

            foreach (var server in bootstrap.AppServers)
            {
                if (server.State == ServerState.Running)
                {
                    SetConsoleColor(ConsoleColor.Green);
                    Console.WriteLine("- {0} has been started", server.Name);
                }
                else
                {
                    SetConsoleColor(ConsoleColor.Red);
                    Console.WriteLine("- {0} failed to start", server.Name);
                }
            }

            Console.ResetColor();
            Console.WriteLine("-------------------------------------------------------------------");

            Console.ResetColor();
            Console.WriteLine("Enter key 'quit' to stop the NRack.Server.");

            RegisterCommands();

            ReadConsoleCommand(bootstrap);

            bootstrap.Stop();

            Console.WriteLine("The NRack.Server has been stopped!");
        }
        /// <summary>
        /// 初始化Socket服务
        /// <code>
        /// SocketServiceContainer.Create(CurrentAddinConfiguration);
        /// </code>
        /// </summary>
        /// <param name="currentAddinConfig"></param>
        public static void Create(System.Configuration.Configuration currentAddinConfig)
        {
            IConfigurationSource configSource = currentAddinConfig.GetSection(SocketSection.SectionName) as IConfigurationSource;

            if (configSource == null)
            {
                return;
            }
            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap(configSource);

            bootstrap.Initialize(new Log4NetLogFactory());
            StartResult result = bootstrap.Start();
        }
Exemplo n.º 21
0
 public static void Start()
 {
     bootstrap = BootstrapFactory.CreateBootstrap();
     if (!bootstrap.Initialize())
     {
         Console.WriteLine("Failed to initialize!");
         return;
     }
     ouSrv = (OpcUserServer)bootstrap.AppServers.First();
     ouSrv.NewSessionConnected += new SessionHandler<OpcUserSession>(SessionConnected);
     ouSrv.SessionClosed += new SessionHandler<OpcUserSession, CloseReason>(SessionClosed);
     StartResult result = bootstrap.Start();
 }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the server!");

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

            IBootstrap bootstrap = null;

            try {
                bootstrap = BootstrapFactory.CreateBootstrap();
            } catch (System.Configuration.ConfigurationErrorsException ex) {
                Console.WriteLine(ex.Message);
                Environment.Exit(-1);
            }

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("Failed to initialize!");
                Console.ReadKey();
                return;
            }

            var result = bootstrap.Start();

            Console.WriteLine("Start result: {0}!", result);

            if (result == StartResult.Failed)
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("Press key 'q' to stop it!");

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


            Console.WriteLine();

            //Stop the appServer
            bootstrap.Stop();

            Console.WriteLine("The server was stopped!");
            Console.ReadKey();
        }
Exemplo n.º 23
0
        public override bool OnStart()
        {
            Trace.TraceInformation("WorkerRole1 is starting");
            NewRelic.Api.Agent.NewRelic.SetTransactionName("Worker", "OnStart"); var watch = Stopwatch.StartNew();

            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 200;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            m_Bootstrap = BootstrapFactory.CreateBootstrap();

            var endpoints = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.ToDictionary
                (p => p.Key, p => p.Value.IPEndpoint);
            if (!m_Bootstrap.Initialize(endpoints))
            {
                Trace.WriteLine("Failed to initialize SuperSocket!", "Error");
                NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric("OnStart", watch.ElapsedMilliseconds);
                return false;
            }

            var result = m_Bootstrap.Start();

            switch (result)
            {
                case (StartResult.None):
                    Trace.WriteLine("No server is configured, please check you configuration!");
                    NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric("OnStart", watch.ElapsedMilliseconds);
                    return false;

                case (StartResult.Success):
                    Trace.WriteLine("The server has been started!");
                    break;

                case (StartResult.Failed):
                    Trace.WriteLine("Failed to start SuperSocket server! Please check error log for more information!");
                    NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric("OnStart", watch.ElapsedMilliseconds);
                    return false;

                case (StartResult.PartialSuccess):
                    Trace.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!");
                    break;
            }

            Trace.TraceInformation("WorkerRole1 has started");
            NewRelic.Api.Agent.NewRelic.RecordResponseTimeMetric("OnStart", watch.ElapsedMilliseconds);

            return base.OnStart();
        }
Exemplo n.º 24
0
        public void StartSuperWebSocketByProgramming()
        {
            var socketServer = new WebSocketServer();

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

            socketServer.Setup(port);

            m_Bootstrap = new DefaultBootstrap(new RootConfig(), new IWorkItem[] { socketServer });

            m_Bootstrap.Start();
        }
Exemplo n.º 25
0
        public void StartSuperWebSocketByProgramming()
        {
            var socketServer = new WebSocketServer();

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

            socketServer.Setup(port);

            m_Bootstrap = new DefaultBootstrap(new RootConfig(), new IWorkItem[] { socketServer });

            m_Bootstrap.Start();
        }
Exemplo n.º 26
0
        protected void StartServer()
        {
            if (!bootstrap.Initialize())
            {
                return;
            }

            var result = bootstrap?.Start();

            if (result == StartResult.Failed)
            {
                return;
            }
        }
Exemplo n.º 27
0
        private void ServerManager_Load(object sender, EventArgs e)
        {
            //var serverConfig = new ServerConfig
            //{
            //    Port = 2012,//set the listening port
            //    Ip = "192.168.10.159"
            //};
            bootstrap = BootstrapFactory.CreateBootstrap();
            if (!bootstrap.Initialize())
            {
                txtMsg.Items.Add("Failed to initialize!");
                //Console.ReadKey();
                return;
            }

            var result = bootstrap.Start();

            //TelnetServer sss = bootstrap.AppServers.First() as TelnetServer;
            //sss.NewSessionConnected += sss_NewSessionConnected;
            txtMsg.Items.Add(string.Format("Start result: {0}!", result));

            if (result == StartResult.Failed)
            {
                txtMsg.Items.Add("Failed to start!");
                // Console.ReadKey();
                return;
            }
            //if (!appServer.Setup(2012))
            //{
            //    txtMsg.Items.Add("Failed to setup!");
            //    return;
            //}
            appServer = bootstrap.AppServers.First() as ESOPServer;
            appServer.NewSessionConnected += new SessionHandler <ESOPSession>(appServer_NewSessionConnected);
            appServer.NewRequestReceived  += new RequestHandler <ESOPSession, StringRequestInfo>(appServer_NewRequestReceived);
            appServer.SessionClosed       += appServer_SessionClosed;

            //Try to start the appServer
            //if (!appServer.Start())
            //{
            //    txtMsg.Items.Add("Failed to start!");
            //    return;
            //}

            //txtMsg.Items.Add("The server started successfully");
        }
Exemplo n.º 28
0
        void StartSuperWebSocketByProgramming()
        {
            m_Bootstrap = new DefaultBootstrap();

            var socketServer = new WebSocketServer();

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

            var secureSocketServer = new WebSocketServer();

            m_Bootstrap.Initialize(new RootConfig(), new IAppServer[] { socketServer, secureSocketServer },
                                   new IServerConfig[]
            {
                new ServerConfig
                {
                    Name = "SuperWebSocket",
                    Ip   = "Any",
                    Port = 2011,
                    Mode = SocketMode.Tcp
                },
                new ServerConfig
                {
                    Name        = "SecureSuperWebSocket",
                    Ip          = "Any",
                    Port        = 2012,
                    Mode        = SocketMode.Tcp,
                    Security    = "tls",
                    Certificate = new SuperSocket.SocketBase.Config.CertificateConfig
                    {
                        FilePath  = Server.MapPath("~/localhost.pfx"),
                        Password  = "******",
                        IsEnabled = true
                    }
                }
            });

            secureSocketServer.NewSessionConnected += secureSocketServer_NewSessionConnected;
            secureSocketServer.SessionClosed       += secureSocketServer_SessionClosed;

            Application["WebSocketPort"]       = socketServer.Config.Port;
            Application["SecureWebSocketPort"] = secureSocketServer.Config.Port;

            m_Bootstrap.Start();
        }
Exemplo n.º 29
0
        void StartSuperWebSocketByConfig()
        {
            m_Bootstrap = BootstrapFactory.CreateBootstrap();

            if (!m_Bootstrap.Initialize())
                return;

            var socketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SuperWebSocket")) as WebSocketServer;

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

            m_WebSocketServer = socketServer;

            m_Bootstrap.Start();
        }
Exemplo n.º 30
0
        public void Init()
        {
            //Console.WriteLine("Press any key to start the server!");

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

            bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("服务器未初始化");
                Console.ReadKey();
                return;
            }
            var result = bootstrap.Start();

            Console.WriteLine("socket服务器启动结果{0}", result);

            if (result == StartResult.Failed)
            {
                Console.WriteLine("失败!");
                Console.ReadKey();
                return;
            }
            SeverTimer serverTimer = new SeverTimer();

            serverTimer.Init();

            Console.WriteLine("按Q键退出服务器");

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

            Console.WriteLine();

            //Stop the appServer
            bootstrap.Stop();

            Console.WriteLine("服务器正常停止!");
            Console.ReadKey();
        }
Exemplo n.º 31
0
        void StartSuperWebSocketByConfig()
        {
            m_Bootstrap = BootstrapFactory.CreateBootstrap();

            if (!m_Bootstrap.Initialize())
            {
                return;
            }

            var socketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SuperWebSocket")) as WebSocketServer;

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

            m_WebSocketServer = socketServer;

            m_Bootstrap.Start();
        }
Exemplo n.º 32
0
        public void TestActiveConnect()
        {
            StartBootstrap(DefaultServerConfig);

            IBootstrap activeServerBootstrap;
            var        activeTargetServerConfig = CreateBootstrap("ActiveConnectServer.config", out activeServerBootstrap);

            Assert.IsTrue(activeServerBootstrap.Initialize());

            var serverConfig  = activeTargetServerConfig.Servers.FirstOrDefault();
            var serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port);

            m_ActiveServerBootstrap = AppDomain.CurrentDomain.GetData("Bootstrap") as IBootstrap;

            Assert.AreEqual(StartResult.Success, m_ActiveServerBootstrap.Start());

            var appServer = BootStrap.AppServers.FirstOrDefault() as TestServer;

            var task = appServer.ActiveConnectRemote(serverAddress);

            if (!task.Wait(5000))
            {
                Assert.Fail("Active connect the server timeout");
            }

            Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);

            Assert.AreEqual(true, task.Result.Result);
            Assert.IsNotNull(task.Result.Session);

            Assert.AreEqual(1, m_ActiveServerBootstrap.AppServers.FirstOrDefault().SessionCount);

            var session = task.Result.Session as TestSession;

            var rd = new Random();
            var a  = rd.Next(1, 1000);
            var b  = rd.Next(1, 1000);

            session.Send("ADDR " + a + " " + b);
            Thread.Sleep(500);

            Assert.AreEqual((a + b).ToString(), RESU.Result);
        }
Exemplo n.º 33
0
        private IConfigurationSource SetupBootstrap(string configFile)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            fileMap.ExeConfigFilename = Path.Combine(@"Config", configFile);

            var config       = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var configSource = config.GetSection("socketServer") as IConfigurationSource;

            m_BootStrap = BootstrapFactory.CreateBootstrap(configSource);

            Assert.IsTrue(m_BootStrap.Initialize());

            var result = m_BootStrap.Start();

            Assert.AreEqual(StartResult.Success, result);

            return(configSource);
        }
Exemplo n.º 34
0
        private void StartWebSocketServer()
        {
            var appFolder  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var configPath = Path.Combine(Path.Combine(appFolder, "config"), "supersocket.config");

            _bootstrapFactory = BootstrapFactory.CreateBootstrapFromConfigFile(configPath);
            if (!_bootstrapFactory.Initialize())
            {
                throw new Exception("Failed to initialize");
            }
            (_bootstrapFactory.AppServers.First() as IotWebSocketServer).SetConnectionRegistry(_connectionRegistry, () => _serviceProvider.GetService <CommandExecutor>());

            var result = _bootstrapFactory.Start();

            if (result == StartResult.Failed)
            {
                throw new Exception("Failed to start");
            }
        }
Exemplo n.º 35
0
        public void TestActiveConnect()
        {
            StartBootstrap(DefaultServerConfig);

            IBootstrap activeServerBootstrap;
            var activeTargetServerConfig = CreateBootstrap("ActiveConnectServer.config", out activeServerBootstrap);

            Assert.IsTrue(activeServerBootstrap.Initialize());

            var serverConfig = activeTargetServerConfig.Servers.FirstOrDefault();
            var serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port);

            m_ActiveServerBootstrap = AppDomain.CurrentDomain.GetData("Bootstrap") as IBootstrap;

            Assert.AreEqual(StartResult.Success, m_ActiveServerBootstrap.Start());

            var appServer = BootStrap.AppServers.FirstOrDefault() as TestServer;

            var task = appServer.ActiveConnectRemote(serverAddress);

            if (!task.Wait(5000))
            {
                Assert.Fail("Active connect the server timeout");
            }

            Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);

            Assert.AreEqual(true, task.Result.Result);
            Assert.IsNotNull(task.Result.Session);

            Assert.AreEqual(1, m_ActiveServerBootstrap.AppServers.FirstOrDefault().SessionCount);

            var session = task.Result.Session as TestSession;

            var rd = new Random();
            var a = rd.Next(1, 1000);
            var b = rd.Next(1, 1000);
            session.Send("ADDR " + a + " " + b);
            Thread.Sleep(500);

            Assert.AreEqual((a + b).ToString(), RESU.Result);
        }
Exemplo n.º 36
0
        public void CreateStartServer()
        {
            ActiveServerBootstrap = BootstrapFactory.CreateBootstrap();

            if (!ActiveServerBootstrap.Initialize())
            {
                Console.WriteLine(string.Format("서버 초기화 실패"), LOG_LEVEL.ERROR);
                return;
            }
            else
            {
                var refAppServer = ActiveServerBootstrap.AppServers.FirstOrDefault() as MainServer;
                MainLogger = refAppServer.Logger;
                WriteLog("서버 초기화 성공", LOG_LEVEL.INFO);
            }


            var result = ActiveServerBootstrap.Start();

            if (result != StartResult.Success)
            {
                MainServer.WriteLog(string.Format("서버 시작 실패"), LOG_LEVEL.ERROR);
                return;
            }
            else
            {
                WriteLog("서버 시작 성공", LOG_LEVEL.INFO);
            }

            WriteLog(string.Format("서버 생성 및 시작 성공"), LOG_LEVEL.INFO);


            ChatServerEnvironment.Setting();

            StartRemoteConnect();

            var appServer = ActiveServerBootstrap.AppServers.FirstOrDefault() as MainServer;

            InnerMessageHostProgram.ServerStart(ChatServerEnvironment.ChatServerUniqueID, appServer.Config.Port);

            ClientSession.CreateIndexPool(appServer.Config.MaxConnectionNumber);
        }
Exemplo n.º 37
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 100;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig;

            m_Bootstrap = BootstrapFactory.CreateBootstrap(serverConfig);

            if (!m_Bootstrap.Initialize(ResolveServerConfig))
            {
                Trace.WriteLine("Failed to initialize SuperSocket!", "Error");
                return false;
            }

            var result = m_Bootstrap.Start();

            switch (result)
            {
                case (StartResult.None):
                    Trace.WriteLine("No server is configured, please check you configuration!");
                    return false;

                case (StartResult.Success):
                    Trace.WriteLine("The server has been started!");
                    break;

                case (StartResult.Failed):
                    Trace.WriteLine("Failed to start SuperSocket server! Please check error log for more information!");
                    return false;

                case (StartResult.PartialSuccess):
                    Trace.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!");
                    break;
            }

            return base.OnStart();
        }
Exemplo n.º 38
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            m_Bootstrap = BootstrapFactory.CreateBootstrap();

            if (!m_Bootstrap.Initialize(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.ToDictionary(
                p => p.Key,
                p => p.Value.IPEndpoint)))
            {
                Trace.WriteLine("Failed to initialize SuperWebSocket!", "Error");
                return false;
            }

            var result = m_Bootstrap.Start();

            switch (result)
            {
                case (StartResult.None):
                    Trace.WriteLine("No server is configured, please check you configuration!");
                    return false;

                case (StartResult.Success):
                    Trace.WriteLine("The server has been started!");
                    break;

                case (StartResult.Failed):
                    Trace.WriteLine("Failed to start SuperWebSocket server! Please check error log for more information!");
                    return false;

                case (StartResult.PartialSuccess):
                    Trace.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!");
                    break;
            }

            return base.OnStart();
        }
Exemplo n.º 39
0
        void StartSuperWebSocketByConfig()
        {
            m_Bootstrap = new DefaultBootstrap();

            var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig;
            if (!m_Bootstrap.Initialize(serverConfig))
                return;

            var socketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SuperWebSocket")) as WebSocketServer;
            var secureSocketServer = m_Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("SecureSuperWebSocket")) as WebSocketServer;

            Application["WebSocketPort"] = socketServer.Config.Port;
            Application["SecureWebSocketPort"] = secureSocketServer.Config.Port;

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

            secureSocketServer.NewSessionConnected += secureSocketServer_NewSessionConnected;
            secureSocketServer.SessionClosed += secureSocketServer_SessionClosed;

            m_Bootstrap.Start();
        }
Exemplo n.º 40
0
        void StartSuperWebSocketByProgramming()
        {
            var rootConfig = new RootConfig();

            var socketServer = new WebSocketServer();

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

            socketServer.Setup(rootConfig,
                new ServerConfig
                    {
                        Name = "SuperWebSocket",
                        Ip = "Any",
                        Port = 2011,
                        Mode = SocketMode.Tcp
                    });

            var secureSocketServer = new WebSocketServer();
            secureSocketServer.NewSessionConnected += secureSocketServer_NewSessionConnected;
            secureSocketServer.SessionClosed += secureSocketServer_SessionClosed;

            secureSocketServer.Setup(rootConfig, new ServerConfig
                    {
                        Name = "SecureSuperWebSocket",
                        Ip = "Any",
                        Port = 2012,
                        Mode = SocketMode.Tcp,
                        Security = "tls",
                        Certificate = new SuperSocket.SocketBase.Config.CertificateConfig
                        {
                            FilePath = Server.MapPath("~/localhost.pfx"),
                            Password = "******"
                        }
                    });

            m_Bootstrap = new DefaultBootstrap(new RootConfig(), new IWorkItem[] { socketServer, secureSocketServer });

            Application["WebSocketPort"] = socketServer.Config.Port;
            Application["SecureWebSocketPort"] = secureSocketServer.Config.Port;

            m_Bootstrap.Start();
        }
Exemplo n.º 41
0
        private IConfigurationSource SetupBootstrap(string configFile)
        {
            var fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = Path.Combine(@"Config", configFile);

            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var configSource = config.GetSection("socketServer") as IConfigurationSource;

            m_BootStrap = BootstrapFactory.CreateBootstrap(configSource);

            Assert.IsTrue(m_BootStrap.Initialize());

            var result = m_BootStrap.Start();

            Assert.AreEqual(StartResult.Success, result);

            return configSource;
        }
Exemplo n.º 42
0
        public void TestActiveConnect()
        {
            StartBootstrap(DefaultServerConfig);

            IBootstrap activeServerBootstrap;
            var activeTargetServerConfig = CreateBootstrap("ActiveConnectServer.config", out activeServerBootstrap);

            Assert.IsTrue(activeServerBootstrap.Initialize());

            var serverConfig = activeTargetServerConfig.Servers.FirstOrDefault();
            var serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port);

            m_ActiveServerBootstrap = activeServerBootstrap;

            Assert.AreEqual(StartResult.Success, m_ActiveServerBootstrap.Start());

            var appServer = BootStrap.AppServers.FirstOrDefault() as TestServer;

            var task = appServer.ActiveConnectRemote(serverAddress);

            if (!task.Wait(5000))
            {
                Assert.Fail("Active connect the server timeout");
            }

            Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);

            Assert.AreEqual(true, task.Result.Result);
            Assert.IsNotNull(task.Result.Session);

            var remoteServer = m_ActiveServerBootstrap.AppServers.FirstOrDefault() as TestServer;

            Thread.Sleep(100);

            Assert.AreEqual(1, appServer.SessionCount);
            Assert.AreEqual(1, remoteServer.SessionCount);

            var session = task.Result.Session as TestSession;

            var rd = new Random();
            var a = rd.Next(1, 1000);
            var b = rd.Next(1, 1000);
            session.Send("ADDR " + a + " " + b);
            Thread.Sleep(500);

            Assert.AreEqual((a + b).ToString(), RESU.Result);

            var resetEvent = new AutoResetEvent(false);

            //Reconnect
            session.SocketSession.Closed += (s, c) =>
                {
                    resetEvent.WaitOne();
                    Thread.Sleep(5000);
                    var t = appServer.ActiveConnectRemote(serverAddress);
                    t.ContinueWith((x) =>
                        {
                            if (x.Exception != null)
                                Console.WriteLine(x.Exception.InnerException.Message);

                            resetEvent.Set();
                        });
                };

            foreach (var s in remoteServer.GetAllSessions())
            {
                s.Close();
            }

            Thread.Sleep(500);

            Assert.AreEqual(0, appServer.SessionCount);
            Assert.AreEqual(0, remoteServer.SessionCount);

            resetEvent.Set();
            Thread.Sleep(500);
            resetEvent.WaitOne();

            Thread.Sleep(500);

            Assert.AreEqual(1, appServer.SessionCount);
            Assert.AreEqual(1, remoteServer.SessionCount);

        }