/// <summary>
        /// 添加ws路径组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="bufferSize"></param>
        /// <returns></returns>
        public static WebSocketServiceHost AddWebSocketService <T>(string path, int bufferSize = 4096) where T : WebSocketBehavior, new()
        {
            WebSocketServiceHost <T> host = new WebSocketServiceHost <T>(path, bufferSize);

            ServiceHosts.Add(path, host);
            return(host);
        }
        public MapDataServer()
        {
            httpServer = new HttpServer(WebMapConfig.SERVER_PORT);
            httpServer.AddWebSocketService <WebSocketHandler>("/");
            httpServer.KeepClean = true;

            webSocketHandler = httpServer.WebSocketServices["/"];

            //Debug.Log($"WebMap: MapDataServer() interval={WebMapConfig.PLAYER_UPDATE_INTERVAL}");
            publicRoot = Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "web");
            fileCache  = new Dictionary <string, byte[]>();

            httpServer.OnGet += (sender, e) =>
            {
                if (ProcessSpecialAPIRoutes(e))
                {
                    return;
                }

                if (ProcessSpecialRoutes(e))
                {
                    return;
                }
                ServeStaticFiles(e);
            };

            httpServer.OnPost += (sender, e) =>
            {
                ProcessSpecialAPIRoutes(e);
            };
        }
Exemple #3
0
        static void Main(string[] args)
        {
            LogConsole._Load();
            LogDebug.debug = true;
            _SQL.Init("localhost", "root", "13456", "dbbase", 3306);
            var wssv = new WebSocketServiceHost <Serverb>("ws://192.168.1.5:8085");

            wssv.OnError += (sender, e) =>
            {
                Console.WriteLine("[WS] error", "WS: Error: " + e.Message, "notification-message-im");
            };

            wssv.Start();

            Console.WriteLine("WebSocket Server listening on port: {0}", wssv.Port);
            while (true)
            {
                Thread.Sleep(1000);

                string _comm = Console.ReadLine();
                switch (_comm)
                {
                case "count":
                    Console.WriteLine("Users Online: {0}", Users.Count());
                    break;

                default:
                    break;
                }
            }
            //Console.ReadKey();
        }
Exemple #4
0
        private void wsBroadcast(object obj, WebSocketServiceHost host)
        {
            var json = JToken.FromObject(obj);
            var str  = json.ToString(Newtonsoft.Json.Formatting.None);

            host.Sessions.BroadcastAsync(str, null);
        }
Exemple #5
0
 public VebSocketService(IHDEHost hdehost, WebSocketServiceHost service)
 {
     this.Service = service;
     this.HDEHost = hdehost;
     this.Service.Sessions.OnConnectedClient += onConnectedClient;
     this.Service.Sessions.OnClosedClient    += onClosedClient;
     this.HDEHost.MainLoop.OnUpdateView      += onUpdateView;
 }
Exemple #6
0
    public void SendMessage(string serviceId, string message)
    {
        WebSocketServiceHost host = GetServiceHost(currentService);

        if (host != null)
        {
            host.Sessions.SendTo(message, serviceId);
        }
    }
Exemple #7
0
        public MapDataServer()
        {
            httpServer = new HttpServer(SERVER_PORT);
            httpServer.AddWebSocketService <WebSocketHandler>("/");
            httpServer.KeepClean = true;

            webSocketHandler = httpServer.WebSocketServices["/"];

            broadcastTimer = new System.Threading.Timer(e => {
                string dataString = "";
                players.ForEach(player => {
                    ZDO zdoData = null;
                    try {
                        zdoData = ZDOMan.instance.GetZDO(player.m_characterID);
                    } catch { }

                    if (zdoData != null)
                    {
                        Vector3 pos     = zdoData.GetPosition();
                        float maxHealth = zdoData.GetFloat("max_health", 25f);
                        float health    = zdoData.GetFloat("health", maxHealth);
                        maxHealth       = Mathf.Max(maxHealth, health);

                        if (player.m_publicRefPos)
                        {
                            dataString +=
                                $"{player.m_uid}\n{player.m_playerName}\n{pos.x:0.##},{pos.y:0.##},{pos.z:0.##}\n{health:0.##}\n{maxHealth:0.##}\n\n";
                        }
                        else
                        {
                            dataString += $"{player.m_uid}\n{player.m_playerName}\nhidden\n\n";
                        }
                    }
                });
                if (dataString.Length > 0)
                {
                    webSocketHandler.Sessions.Broadcast("players\n" + dataString.Trim());
                }
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(PLAYER_UPDATE_INTERVAL));

            publicRoot = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty, "web");

            fileCache = new Dictionary <string, byte[]>();

            httpServer.OnGet += (sender, e) => {
                HttpListenerRequest req = e.Request;
                // Debug.Log("~~~ Got GET Request for: " + req.RawUrl);

                if (ProcessSpecialRoutes(e))
                {
                    return;
                }

                ServeStaticFiles(e);
            };
        }
Exemple #8
0
    // not reliable!
    public List <string> GetActiveSessions()
    {
        WebSocketServiceHost host = null;

        wssv.WebSocketServices.TryGetServiceHost("/", out host);
        if (host != null)
        {
            List <string> list = host.Sessions.ActiveIDs.ToList();
            return(list);
        }
        return(new List <string>());
    }
Exemple #9
0
    public List <GameService> GetAllGameServices(string service)
    {
        WebSocketServiceHost host = GetServiceHost(service);

        if (host != null && host.BehaviorType == typeof(GameService))
        {
            IEnumerable <GameService> allServices = host.Sessions.Sessions as IEnumerable <GameService>;
            return(allServices.ToList <GameService> ());
        }
        else
        {
            return(null);
        }
    }
Exemple #10
0
        private void OnNewService(object sender, ServiceAddedEventArgs e)
        {
            WebSocketServiceHost wssh = null;

            foreach (WebSocketServiceHost cwssh in this.Server.WebSocketServices.Hosts)
            {
                if (cwssh.Path == e.Path)
                {
                    wssh = cwssh;
                }
            }
            if (wssh != null)
            {
                VebSocketService s = new VebSocketService(this.HDEHost, wssh);
                this.Services.Add(e.Path, s);
            }
        }
Exemple #11
0
        public MapDataServer()
        {
            httpServer = new HttpServer(WebMapConfig.SERVER_PORT);
            httpServer.AddWebSocketService <WebSocketHandler>("/");
            httpServer.KeepClean = true;

            webSocketHandler = httpServer.WebSocketServices["/"];

            broadcastTimer = new System.Threading.Timer((e) => {
                var dataString = "";
                players.ForEach(player => {
                    var zdoData = ZDOMan.instance.GetZDO(player.m_characterID);
                    var pos     = zdoData.GetPosition();
                    if (player.m_publicRefPos)
                    {
                        dataString += $"{player.m_uid}\n{player.m_playerName}\n{pos.x},{pos.y},{pos.z}\n";
                    }
                    else
                    {
                        dataString += $"{player.m_uid}\n{player.m_playerName}\nhidden\n";
                    }
                });
                if (dataString.Length > 0)
                {
                    webSocketHandler.Sessions.Broadcast("players\n" + dataString);
                }
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(WebMapConfig.PLAYER_UPDATE_INTERVAL));

            publicRoot = Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "web");

            fileCache = new Dictionary <string, byte[]>();

            httpServer.OnGet += (sender, e) => {
                var req = e.Request;
                // Debug.Log("~~~ Got GET Request for: " + req.RawUrl);

                if (ProcessSpecialRoutes(e))
                {
                    return;
                }

                ServeStaticFiles(e);
            };
        }
Exemple #12
0
        public bool TryGetValue(string reurl, out WebSocketServiceHost host)
        {
            bool flag = false;

            foreach (KeyValuePair <string, MapRoute> ky in dic)
            {
                string newregurl = ky.Value.Url;
                if (reurl == ky.Value.Url)
                {
                    flag = true;
                    host = ky.Value.Defaults;
                    return(flag);
                }
                else
                {
                    if (ky.Value.Rule == null)
                    {
                        continue;
                    }
                    Type           type  = ky.Value.Rule.GetType();
                    PropertyInfo[] pInfo = type.GetProperties();
                    for (int m = 0; m < pInfo.Length; m++)
                    {
                        PropertyInfo p = pInfo[m];
                        newregurl = newregurl.Replace("{" + p.Name + "}", p.GetValue(ky.Value.Rule, null));
                    }
                    Match match = Regex.Match(reurl, newregurl, RegexOptions.IgnoreCase);
                    if (match != null)
                    {
                        string result = match.Value;
                        if (result == reurl)
                        {
                            flag = true;
                            host = ky.Value.Defaults;
                            return(flag);
                        }
                    }
                }
            }
            host = null;
            return(false);
        }
Exemple #13
0
    public GameService GetGameService(string serviceId)
    {
        WebSocketServiceHost host = GetServiceHost(currentService);

        if (host != null && !string.IsNullOrEmpty(serviceId) && host.BehaviorType == typeof(GameService))
        {
            IWebSocketSession session;
            if (host.Sessions.TryGetSession(serviceId, out session))
            {
                return(session as GameService);
            }
            else
            {
                return(null);
            }
        }
        else
        {
            return(null);
        }
    }
Exemple #14
0
    static void Main(string[] args)
    {
#if Local
        string sqlIp    = "49.233.16.171";
        string severUrl = "127.0.0.1";
#else
        string sqlIp    = "127.0.0.1";
        string severUrl = "172.21.0.7";
#endif
        //连接数据库
        if (!DbManager.Connect("shan_guo_sha", sqlIp, 3306, "root", ""))
        {
            return;
        }
        //启动服务器
        WebSocketServer wssv = new WebSocketServer("ws://" + severUrl);
        wssv.AddWebSocketService <GameWebSocketBehavior>("/Login");
        wssv.Start();
        wssv.Log.Level = LogLevel.Info;
        Log            = wssv.Log;
        WebSocketServiceHost webSocketServiceHost = wssv.WebSocketServices["/Login"];
        NetManager.sessionManager = webSocketServiceHost.Sessions;
        Console.WriteLine("服务器启动");
        while (true)
        {
            OnUpdate();
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                if (key.Key == ConsoleKey.Q)
                {
                    break;
                }
            }
        }
        wssv.Stop();
    }
Exemple #15
0
    public void SendMessage(string target, string msg)
    {
        Debug.Log("Sending " + msg + " to session " + target);
        WebSocketServiceHost host = null;

        wssv.WebSocketServices.TryGetServiceHost("/", out host);
        if (host != null)
        {
            if (target == "broadcast")
            {
                host.Sessions.BroadcastAsync(msg, null);
            }
            else
            {
                IWebSocketSession session;
                if (!host.Sessions.TryGetSession(target, out session))
                {
                    Debug.Log("The session could not be found.");
                    return;
                }
                host.Sessions.SendToAsync(msg, target, null);
            }
        }
    }
Exemple #16
0
        protected override void Load(ContainerBuilder builder)
        {
            IGameEngineConfig    config = new GameEngineConfig().LoadConfiguration("test");
            WebSocketServiceHost host   = null;

            builder.RegisterType <ConsoleLoggingService>()
            .InstancePerLifetimeScope()
            .As <ILoggingService>();

            builder.RegisterType <ConsoleRenderer>()
            .SingleInstance()
            .As <IRenderer>();

            builder
            .RegisterType <GameEngineConfig>()
            .SingleInstance()
            .As <IGameEngineConfig>();

            builder
            .RegisterType <InternalWebSocketClient>()
            .SingleInstance()
            .AsSelf();

            builder.RegisterType <WebSocketServer>()
            .SingleInstance()
            .As <WebSocketServer>()
            .WithParameters(new Parameter[]
            {
                new NamedParameter("address", IPAddress.Parse("127.0.0.1")),
                new NamedParameter("port", 2137),
            })
            .OnActivated(args =>
            {
                Type[] allAvailableCommands   = Command.GetAvailableCommands();
                Type[] allAvailableParameters = Command.GetAvailableParameters();

                WebSocketServer instance = args.Instance;
                instance.AddWebSocketService <WebSocketCommandReceiver>("/command", (c) =>
                {
                    c.Initialize(new InputStringCommandResolver(allAvailableCommands, allAvailableParameters), CommandFactory);
                });
                instance.Start();
                instance.WebSocketServices.TryGetServiceHost("/command", out host);
            });

            builder
            .RegisterType <SimpleGameServer>()
            .SingleInstance()
            .As <SimpleGameServer>()
            .OnActivated(a => a.Instance.AddHost(host));


            builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
            .Where(type => type.IsSubclassOf(typeof(GameLogicBehaviour)))
            .As <GameLogicBehaviour>()
            .InstancePerDependency();

            builder.RegisterType <SimpleGameEngine>()
            .SingleInstance()
            .WithParameters(new[]
            {
                new NamedParameter("config", config),
            })
            .AsSelf()
            .OnActivated(engineBuilder => engineBuilder.Instance.Run());
        }
Exemple #17
0
        private void Init()
        {
            // Create a new instance of the HttpServer class.
            //
            // If you would like to provide the secure connection, you should
            // create a new instance with the 'secure' parameter set to true,
            // or an https scheme HTTP URL.

            httpsv = new HttpServer(WEB_SOCK_PORT);
            //var httpsv = new HttpServer (5963, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.Any, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.Any, 5963, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Any, 5963, true);

            //var httpsv = new HttpServer ("http://0.0.0.0:4649");
            //var httpsv = new HttpServer ("https://0.0.0.0:5963");

            //var httpsv = new HttpServer ("http://[::0]:4649");
            //var httpsv = new HttpServer ("https://[::0]:5963");

            //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.Loopback, 5963, true);

            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 4649);
            //var httpsv = new HttpServer (System.Net.IPAddress.IPv6Loopback, 5963, true);

            //var httpsv = new HttpServer ("http://localhost:4649");
            //var httpsv = new HttpServer ("https://localhost:5963");

            //var httpsv = new HttpServer ("http://127.0.0.1:4649");
            //var httpsv = new HttpServer ("https://127.0.0.1:5963");

            //var httpsv = new HttpServer ("http://[::1]:4649");
            //var httpsv = new HttpServer ("https://[::1]:5963");
#if DEBUG
            // To change the logging level.
            //httpsv.Log.Level = LogLevel.Trace;

            // To change the wait time for the response to the WebSocket Ping or Close.
            //httpsv.WaitTime = TimeSpan.FromSeconds (2);

            // Not to remove the inactive WebSocket sessions periodically.
            //httpsv.KeepClean = false;
#endif
            // To provide the secure connection.

            /*
             * var cert = ConfigurationManager.AppSettings["ServerCertFile"];
             * var passwd = ConfigurationManager.AppSettings["CertFilePassword"];
             * httpsv.SslConfiguration.ServerCertificate = new X509Certificate2 (cert, passwd);
             */

            // To provide the HTTP Authentication (Basic/Digest).

            /*
             * httpsv.AuthenticationSchemes = AuthenticationSchemes.Basic;
             * httpsv.Realm = "WebSocket Test";
             * httpsv.UserCredentialsFinder = id => {
             *  var name = id.Name;
             *
             *  // Return user name, password, and roles.
             *  return name == "nobita"
             *         ? new NetworkCredential (name, "password", "gunfighter")
             *         : null; // If the user credentials aren't found.
             * };
             */

            // To resolve to wait for socket in TIME_WAIT state.
            //httpsv.ReuseAddress = true;

            // Set the document root path.
            //httpsv.DocumentRootPath = ConfigurationManager.AppSettings["DocumentRootPath"];

            // Set the HTTP GET request event.
            httpsv.OnGet += new EventHandler <HttpRequestEventArgs>(OnHttpGet);

            // Add the WebSocket services.
            httpsv.AddWebSocketService <WSService>("/WSService");

            // Add the WebSocket service with initializing.

            /*
             * httpsv.AddWebSocketService<Chat> (
             * "/Chat",
             * () =>
             *  new Chat ("Anon#") {
             *    // To send the Sec-WebSocket-Protocol header that has a subprotocol name.
             *    Protocol = "chat",
             *    // To ignore the Sec-WebSocket-Extensions header.
             *    IgnoreExtensions = true,
             *    // To emit a WebSocket.OnMessage event when receives a ping.
             *    EmitOnPing = true,
             *    // To validate the Origin header.
             *    OriginValidator = val => {
             *        // Check the value of the Origin header, and return true if valid.
             *        Uri origin;
             *        return !val.IsNullOrEmpty ()
             *               && Uri.TryCreate (val, UriKind.Absolute, out origin)
             *               && origin.Host == "localhost";
             *      },
             *    // To validate the cookies.
             *    CookiesValidator = (req, res) => {
             *        // Check the cookies in 'req', and set the cookies to send to
             *        // the client with 'res' if necessary.
             *        foreach (Cookie cookie in req) {
             *          cookie.Expired = true;
             *          res.Add (cookie);
             *        }
             *
             *        return true; // If valid.
             *      }
             *  }
             * );
             */

            //
            wss = httpsv.WebSocketServices["/WSService"];
        }
Exemple #18
0
    public AccumDataBuffer(WebSocketServiceHost serviceSession, string sessionId)
    {
        m_ServiceSession = serviceSession;

        m_SessionID = sessionId;
    }
 internal void AddHost(WebSocketServiceHost host) => Host = host;
Exemple #20
0
 public void Add(string name, string url, WebSocketServiceHost defaults, object rule)
 {
     dic.Add(name, new MapRoute(name, url, defaults, rule));
 }
 public WebSocketContext(WebSocketServiceManager webSocketServiceManager)
 {
     _webSocketServiceHost = webSocketServiceManager.Hosts
                             .Single(h => h.Type.GetInterface(typeof(T).Name) != null);
 }
Exemple #22
0
        static void Main(string[] args)
        {
            LogConsole._Load();
            PATH = Environment.CurrentDirectory.ToString();
            Inix ini = null;

            #region Load Settings
            try
            {
                if (File.Exists(PATH + @"\Settings\Settings.ini"))
                {
                    ini    = new Inix(PATH + @"\Settings\Settings.ini");
                    LSPort = ini.GetValue("Server", "port", 9002).ToString();
                    LSIP   = ini.GetValue("Server", "ip", "localhost").ToString();

                    MIp   = ini.GetValue("MySql", "ip", "localhost").ToString();
                    MUser = ini.GetValue("MySql", "user", "root").ToString();
                    MPass = ini.GetValue("MySql", "pass", "").ToString();
                    MDb   = ini.GetValue("MySql", "db", "db_clone").ToString();
                    MPort = Convert.ToInt32(ini.GetValue("MySql", "port", 3306));

                    debug = Convert.ToBoolean(ini.GetValue("Console", "debug", false));

                    ini = null;
                    LogConsole.Show(LogType.INFO, "Has loaded your ip settings successfully");
                }
                else
                {
                    LogConsole.Show(LogType.ALERT, "Settings.ini could not be found, using default setting");
                }
            }
            catch (Exception excc)
            {
                LogConsole.Show(LogType.ERROR, " {0}", excc.ToString());
                return;
            }
            #endregion

            PacketsManager  = new Packets.PacketsManager();
            SessionsManager = new Components.SessionsManager();
            ChannelManager  = new ChannelManager();

            _SQL.Init(MIp, MUser, MPass, MDb, MPort);

            //MapsL.LoadMaps.Load();


            WSurl = WSurl + LSIP + ":" + LSPort;

            var wssv = new WebSocketServiceHost <Serverb>(WSurl);

            wssv.OnError += (sender, e) =>
            {
                LogConsole.Show(LogType.ERROR, "[WS]: Error {0} ", e.Message);
            };

            wssv.Start();
            LogConsole.Show(LogType.ALERT, "Server Listening on port: {0}", wssv.Port);

            _LoopThrreading          = new Thread(new ThreadStart(Program.LoopConsole));
            _LoopThrreading.Priority = ThreadPriority.BelowNormal;
            _LoopThrreading.Start();

            while (true)
            {
                Thread.Sleep(1000);

                string _comm = Console.ReadLine();
                switch (_comm)
                {
                case "online":
                    //LogConsole.Show(LogType.INFO, "Users Online: {0}", Users.Count());
                    break;

                default:
                    break;
                }
            }
        }