コード例 #1
0
        public Manager()
        {
            // initialize WebSocket services
            Server.AddWebSocketService <Session>("/");
            Session.OnAuthorization     += OnAuthorization;
            Session.OnClientInitialized += OnClientInitialized;
            Session.OnClientRegister    += OnClientRegister;
            Session.OnConfigChange      += OnConfigChange;
            Session.OnConfigRegister    += OnConfigRegister;
            Session.OnConfigStart       += OnConfigStart;
            Session.OnConfigStop        += OnConfigStop;
            Session.OnExecutionRequest  += OnExecutionRequest;
            Session.OnExecutionStarted  += OnExecutionStarted;
            Session.OnExecutionStopped  += OnExecutionStopped;
            Session.OnInfo         += OnInfo;
            Session.OnSessionClose += OnSessionClose;
            Session.OnSubscribe    += OnSubscribe;

            // start WebSocket server
            logger.Info("Starting WebSocket server");

            // deactivate output from WebSocket library
            Server.Log.Output = (_, __) => { };
            Server.Start();

            SessionManager = Server.WebSocketServices["/"].Sessions;

            InitializeEBSSocket();
        }
コード例 #2
0
 public void Broadcast(Message message, GameInstanceRef gameInstanceRef, bool meToo)
 {
     try
     {
         Player currentPlayer = GetCurrentSessionPlayer();
         string msg           = JsonConvert.SerializeObject(message);
         WebSocketSessionManager sessionManager = this.Sessions;
         foreach (Player player in Server.Instance.Players)
         {
             GameInstance playerGameInstance = FindPlayerGameInstance(player);
             if (gameInstanceRef == null || (playerGameInstance != null && gameInstanceRef.Id == playerGameInstance.Id))
             {
                 IWebSocketSession session;
                 if (sessionManager.TryGetSession(player.SessionData.WebsocketSessionId, out session))
                 {
                     if (player.Id == this.GetCurrentSessionPlayer().Id&& !meToo)
                     {
                         continue;
                     }
                     //LogMessage($"Sending to {player.Name} msg={JsonConvert.SerializeObject(msg)}");
                     session.Context.WebSocket.Send(msg);
                 }
             }
         }
     }
     catch (Exception e)
     {
         LogMessage(e.Message);
     }
 }
コード例 #3
0
        private void notifyAboutProductActionResult(Product product)
        {
            if (product.currentHighestBid != null)
            {
                User winner = product.currentHighestBid.bidder;
                WebSocketSessionManager allSessions = getAllSessions();
                if (allSessions == null)
                {
                    return;
                }
                allSessions.SendTo(
                    JsonConvert.SerializeObject(new ProductAuctionResultWrapper(product, true))
                    , winner.sessionID);

                foreach (var userEntry in this.itsModel.connectedUsers)
                {
                    User connectedUser = userEntry.Value;
                    if (!connectedUser.Equals(winner))
                    {
                        allSessions.SendTo(
                            JsonConvert.SerializeObject(new ProductAuctionResultWrapper(product, false))
                            , connectedUser.sessionID);
                    }
                }
            }
        }
コード例 #4
0
        protected override void OnOpen()
        {
            if (_wsMan == null)
            {
                _wsMan = Sessions;
            }
            string sid = null;

            if (Context.CookieCollection["sessionId"] != null)
            {
                sid = Context.CookieCollection["sessionId"].Value;
            }
            _remoteEndPoint = Context.UserEndPoint;
            {
                System.Net.IPAddress remIP;
                if (Context.Headers.Contains("X-Real-IP") && System.Net.IPAddress.TryParse(Context.Headers["X-Real-IP"], out remIP))
                {
                    _remoteEndPoint = new System.Net.IPEndPoint(remIP, _remoteEndPoint.Port);
                }
            }
            _ses = Session.Get(sid, _remoteEndPoint, false);
            if (_ses != null)
            {
                Send((new MessageV04(MessageV04.Cmd.Ack, 0, _ses.id)).ToString());
            }
            else
            {
                Send((new MessageV04(MessageV04.Cmd.Info, 0, _hostName)).ToString());
            }
            if (_verbose.As <bool>())
            {
                X13.lib.Log.Debug("{0} connect webSocket", _ses.owner.name);
            }
        }
コード例 #5
0
        internal void Start(WebSocketContext context, WebSocketSessionManager sessions)
        {
            if (_websocket != null)
            {
                _websocket.Log.Error("A session instance cannot be reused.");
                context.WebSocket.Close(HttpStatusCode.ServiceUnavailable);

                return;
            }

            _context  = context;
            _sessions = sessions;

            _websocket = context.WebSocket;
            _websocket.CustomHandshakeRequestChecker = checkHandshakeRequest;
            _websocket.EmitOnPing       = _emitOnPing;
            _websocket.IgnoreExtensions = _ignoreExtensions;
            _websocket.Protocol         = _protocol;

            var waitTime = sessions.WaitTime;

            if (waitTime != _websocket.WaitTime)
            {
                _websocket.WaitTime = waitTime;
            }

            _websocket.OnOpen    += onOpen;
            _websocket.OnMessage += onMessage;
            _websocket.OnError   += onError;
            _websocket.OnClose   += onClose;

            _websocket.InternalAccept();
        }
コード例 #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebSocketServiceHost"/> class
        /// with the specified <paramref name="path"/> and <paramref name="log"/>.
        /// </summary>
        /// <param name="path">
        /// A <see cref="string"/> that represents the absolute path to the service.
        /// </param>
        /// <param name="log">
        /// A <see cref="Logger"/> that represents the logging function for the service.
        /// </param>
        protected WebSocketServiceHost(string path, Logger log)
        {
            _path = path;
            _log  = log;

            _sessions = new WebSocketSessionManager(log);
        }
コード例 #7
0
        protected override void OnOpen()
        {
            if (_wsMan == null)
            {
                _wsMan = Sessions;
            }
            string sid = null;

            if (Context.CookieCollection["sessionId"] != null)
            {
                sid = Context.CookieCollection["sessionId"].Value;
            }
            System.Net.IPEndPoint remoteEndPoint = Context.UserEndPoint;
            {
                System.Net.IPAddress remIP;
                if (Context.Headers.Contains("X-Real-IP") && System.Net.IPAddress.TryParse(Context.Headers["X-Real-IP"], out remIP))
                {
                    remoteEndPoint = new System.Net.IPEndPoint(remIP, remoteEndPoint.Port);
                }
            }
            _ses           = Session.Get(sid, remoteEndPoint);
            _subscriptions = new List <Repository.SubRec>();
            Send(string.Concat("I\t", _ses.id, "\t", (string.IsNullOrEmpty(_ses.userName)?(/*_disAnonym.value?"false":*/ "null"):"true")));
            if (WebUI_Pl.verbose)
            {
                X13.Log.Debug("{0} connect webSocket", _ses.owner.name);
            }
        }
コード例 #8
0
 public QueryPool(string query, WebSocketSessionManager sessions, string id)
 {
     _query    = query;
     _sessions = sessions;
     _id       = id;
     _context  = _sessions[_id].Context;
     _parseQuery();
 }
コード例 #9
0
 public static void RegisterSession(this WebSocketSessionManager extendedObject, IWebSocketSession session, Authority authority)
 {
     lock (_sessionLookup)
     {
         _sessionLookup[session.ID]          = session;
         _sessionAuthorityLookup[session.ID] = authority;
     }
 }
コード例 #10
0
ファイル: Program.cs プロジェクト: RokasBalaisis/RaceField
 public void SendAll(WebSocketSessionManager Sessions, JObject data)
 {
     for (int i = 0; i < players.Count; i++)
     {
         data["id"] = players[i].id;
         Sessions.SendTo(data.ToString(), players[i].ID);
     }
 }
コード例 #11
0
 public DispatchManager(DeviceManager DeviceManager)
 {
     webSocket = new WebSocketServer(81);
     webSocket.AddWebSocketService("/", DeviceManager.OnDeviceConnect);
     webSocket.Start();
     sessions           = webSocket.WebSocketServices["/"].Sessions;
     this.DeviceManager = DeviceManager;
 }
コード例 #12
0
        void Start()
        {
            String PlayerServicePath = "players";

            wssv.AddWebSocketService <PlayerService>("/" + PlayerServicePath);

            wssv.Start();
            playerSessions = wssv.WebSocketServices["/" + PlayerServicePath].Sessions;
        }
コード例 #13
0
        public WebSocketRPCRoute(int port, string hubPath, WebSocketSessionManager wssm)
        {
            Port    = port;
            HubPath = hubPath;
            var route = port.ToString() + hubPath;

            Route     = route;
            _sessions = wssm;
        }
コード例 #14
0
        private void Match(string firstPlayer, string secondPlayer, WebSocketSessionManager session)
        {
            string firstPlayerID  = GetPlayerID(firstPlayer);
            string secondPlayerID = GetPlayerID(secondPlayer);

            session.SendTo("playing|" + secondPlayer, firstPlayerID);
            session.SendTo("playing|" + firstPlayer, secondPlayerID);

            Logger.LogEventMsg(firstPlayer + " i " + secondPlayer + " su zapoceli igru");
        }
コード例 #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="user"></param>
 /// <param name="wsSessionID"></param>
 public AbstractSession(IUser user, WsUserName wsUserName, string wsSessionID, WebSocketSessionManager wsSessionManager)
 {
     _wsSessionManager  = wsSessionManager;
     this.WsUserName    = wsUserName;
     this.ClientId      = wsUserName.ClientId;
     this.ClientVersion = Version.Parse(wsUserName.ClientVersion);// 因为前面的流程已经过验证所以可以直接Parse
     this.LoginName     = user.LoginName;
     this.ActiveOn      = DateTime.Now;
     this.WsSessionId   = wsSessionID;
 }
コード例 #16
0
 public void Add(string player, WebSocketSessionManager session)
 {
     Add(player);
     Logger.LogWaitingPlayers(Count);
     if (Count >= 2)
     {
         string otherPlayer = this.Where(x => x != player).ToList()[r.Next(0, Count - 1)];
         Match(player, otherPlayer, session);
         Remove(player);
         Remove(otherPlayer);
     }
 }
コード例 #17
0
        public void notifyAllClientsAboutProductChange()
        {
            WebSocketSessionManager allSessions = getAllSessions();

            if (allSessions == null)
            {
                return;
            }
            allSessions.Broadcast(
                JsonConvert.SerializeObject(new UpdateProductsParamWrapper(itsModel.productsInventory))
                );
        }
コード例 #18
0
        public void OnWebSocketOpen(WebSocketSessionManager app, string cid)
        {
            var results = Database.FetchLatestComments(5).Result;

            app.SendTo(JsonConvert.SerializeObject(
                           new { type = "msg", data = results },
                           Formatting.None,
                           new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            }
                           ), cid);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: RokasBalaisis/RaceField
        public void UpdateClientsMap(WebSocketSessionManager Sessions)
        {
            JObject data = new JObject();

            data["players"]     = MapData.getMapData().getPlayersData();
            data["playerCount"] = players.Count;
            data["type"]        = "mapupdate";
            for (int i = 0; i < players.Count; i++)
            {
                data["id"] = players[i].id;
                Sessions.SendTo(data.ToString(), players[i].ID);
            }
        }
コード例 #20
0
        public WebSocketSessionManager GetClient()
        {
            WebSocketSessionManager result = null;
            var server  = ServiceLocator.GetService <DefaultWSServerMessageListener>().Server;
            var entries = ServiceLocator.GetService <IWSServiceEntryProvider>().GetEntries();
            var entry   = entries.Where(p => p.Type == this.GetType()).FirstOrDefault();

            if (server.WebSocketServices.TryGetServiceHost(entry.Path, out WebSocketServiceHostBase webSocketServiceHost))
            {
                result = webSocketServiceHost.Sessions;
            }
            return(result);
        }
コード例 #21
0
        /// <summary>
        /// 点击发送按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_send_Click(object sender, EventArgs e)
        {
            string sendID = this.textBox_sendID.Text;

            _wsServer.WebSocketServices.TryGetServiceHost("/ConnectDataBase", out wssk);

            WebSocketSessionManager wssm = wssk.Sessions;
            IWebSocketSession       iwss;

            wssm.TryGetSession(sendID, out iwss);

            wssm.SendTo(string.Format("{0}: 来自服务端的消息", "server"), sendID);
            //wssm.PingTo(string.Format("{0}: 来自服务端的消息", "server"), sendID);
        }
コード例 #22
0
        public void OnReceiveMessage(WebSocketSessionManager app, string cid, JToken data)
        {
            if (data["type"] != null && data["type"].ToString().Equals("query"))
            {
                if (data["query"] != null && data["query"].ToString().Equals("face"))
                {
                    var id = data["id"]?.ToObject <int>() ?? 0;
                    if (id <= 0)
                    {
                        return;
                    }
                    var user = Database.PickUserInformation(id);
                    if (!string.IsNullOrEmpty(user?.FaceBase64))
                    {
                        app.SendTo(JsonConvert.SerializeObject(
                                       new
                        {
                            type = "user",
                            data = new[] { user }
                        },
                                       Formatting.None,
                                       new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        }
                                       ), cid);
                    }
                }
            }

            if (data["type"] != null && data["type"].ToString().Equals("broadcast"))
            {
                var json = JsonConvert.SerializeObject(
                    data["body"],
                    Formatting.None,
                    new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
                var token = data["token"]?.ToString();
                if (token.Equals("toshiya14"))
                {
                    app.Broadcast(json);
                }
                else
                {
                    app.SendTo("{\"code\":500,\"msg\":\"Server refused your action.\"}", cid);
                }
            }
        }
コード例 #23
0
 public void RefreshDataGrid(WebSocketSessionManager wsm)
 {
     DataTable dt = GetConnectionTable(wsm);
     {
         this.Invoke(new Action(() =>
         {
             lock (dt.Rows.SyncRoot)
             {
                 dgv_browsers.DataSource = dt.Copy();
             }
             dgv_browsers.Columns[0].Width = 400;
             dgv_browsers.Columns[1].Width = 200;
         }));
     }
 }
コード例 #24
0
 public static void UnregisterSession(this WebSocketSessionManager extendedObject, IWebSocketSession session)
 {
     lock (_sessionLookup)
     {
         string id = session.ID;
         if (_sessionLookup.ContainsKey(id))
         {
             _sessionLookup.Remove(id);
         }
         if (_sessionAuthorityLookup.ContainsKey(id))
         {
             _sessionLookup.Remove(id);
         }
     }
 }
コード例 #25
0
        public static void SendTo <T>(this WebSocketSessionManager webSocketSessionManager, T message, string sessionId)
            where T : class
        {
            if (message == null)
            {
                throw new ArgumentNullException("消息不允许为空");
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                throw new ArgumentNullException("SessionId不允许为空");
            }
            var messageJsonString = JsonConvert.SerializeObject(message);
            var sendData          = Encoding.ASCII.GetBytes(messageJsonString);

            webSocketSessionManager.SendTo(sendData, sessionId);
        }
コード例 #26
0
 /// <summary>
 /// @heart 用于心跳
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected override void OnMessage(object sender, MessageEventArgs e)
 {
     if (e.Data != "@heart")
     {
         Stopwatch wath = new Stopwatch();
         wath.Start();
         DataEventArgs           ea      = new DataEventArgs();
         WebSocketSessionManager session = Sessions;
         try
         {
             dynamic data       = JsonConvert.DeserializeObject <JToken>(e.Data);
             string  name       = data.clazz;
             string  methodname = data.method;
             var     parameters = data.param;
             bool    keeplive   = false;
             ea = Call(name, methodname, null, parameters, ref keeplive);
             if (keeplive)
             {
                 DateTime outTime;
                 if (!RunCall.TryGetValue(name + "." + methodname, out outTime))
                 {
                     Thread th = new Thread(new ParameterizedThreadStart(KeepLiveCall));
                     th.Start(new CallPara {
                         Name = name, MethodName = methodname, Parameters = parameters
                     });
                     RunCall.Add(name + "." + methodname, DateTime.Now);
                 }
             }
             wath.Stop();
             long milli = wath.ElapsedMilliseconds;
             monitor.Write(ea.TaskId, name, methodname, milli, e.Data.Length.ToString());
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex);
             _log.Error(ex);
             ea.StatusCode = StatusCode.Serious;
             ea.LastError  = ex.Message;
         }
         finally
         {
             Console.WriteLine(ea.Json);
             Send(ea.Json);
         }
     }
 }
コード例 #27
0
        protected override void OnGet(HttpRequestEventArgs ev)
        {
            WebSocketSessionManager session = Sessions;

            KeepSession        = true;
            Sessions.KeepClean = true;
            byte[] _buffer = GZipUntil.GetZip(Encoding.UTF8.GetBytes(HtmlHelp("http://" + ev.Request.UserHostName)));
            ev.Response.AddHeader("Content-Encoding", "gzip");
            Cookie cookie = ev.Request.Cookies["SessionId"];

            if (cookie != null)
            {
                ApiService sn = (ApiService)Sessions[cookie.Value];
            }
            session.KeepClean = true;

            ev.Response.WriteContent(_buffer);
        }
コード例 #28
0
        private DataTable GetConnectionTable(WebSocketSessionManager wsm)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ID");
            dt.Columns.Add("EndPoint");
            dt.Columns.Add("State");

            lock (wsm.Sessions)
            {
                foreach (IWebSocketSession session in wsm.Sessions.ToArray())
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = session.ID;
                    dr[1] = session.Context.UserEndPoint;
                    dr[2] = session.State;
                    dt.Rows.Add(dr);
                }
            }
            return(dt);
        }
コード例 #29
0
 public AbstractSessionSet(WebSocketSessionManager wsSessionManager)
 {
     this.WsSessionManager = wsSessionManager;
     VirtualRoot.AddEventPath <CleanTimeArrivedEvent>("打扫时间到,保持清洁", LogEnum.UserConsole, action: message => {
         ClearDeath();
         SendReGetServerAddressMessage(message.NodeAddresses);
     }, this.GetType());
     VirtualRoot.AddEventPath <UserDisabledMqMessage>("收到了UserDisabledMq消息后断开该用户的连接", LogEnum.UserConsole, action: message => {
         if (!string.IsNullOrEmpty(message.LoginName))
         {
             TSession[] toCloses;
             lock (_locker) {
                 toCloses = _dicByWsSessionId.Values.Where(a => a.LoginName == message.LoginName).ToArray();
             }
             foreach (var item in toCloses)
             {
                 item.CloseAsync(CloseStatusCode.Normal, "用户已被禁用");
             }
         }
     }, this.GetType());
 }
コード例 #30
0
    /**
     * Starts listening for websocket connections of controllers, as soon as
     * this game object is awakened.
     */
    void Awake()
    {
        _baseServer = new BaseServer();

        // The `ControllerConnection` class will handle remote controller connections on a different
        // thread.
        _baseServer.AddWebSocketService <ControllerConnection>(
            "/controllers",      // we expect connections on the /controllers path
            connection =>
        {
            // we use this initialization function to pass the message queue
            // to the connection worker and remember the id of the connection
            connection.Initialize(_nextNumericConnectionId++, _incomingConnectionUpdates);
            // ^ NOTICE: As far as I understand it, reference assignments as performed by this method  should be
            //           thread-safe. However, if strange things happen, we should look here first.
            Log("A new connection has been established.");
        });

        // Furthermore, we provide a websocket service offering diagnostic data about the game.
        _baseServer.AddWebSocketService <DiagnosticsConnection>("/diagnostics");

        // Now we need to get a handle to the session manager which
        // keeps track of all connections, so that we can use it later
        // to send data
        WebSocketServiceHost serviceHost;

        if (_baseServer.WebSocketServices.TryGetServiceHost("/controllers", out serviceHost))
        {
            _wssm = serviceHost.Sessions;
        }

        else
        {
            Log("Could not get a hold of the websocket service host. This means we can not send any messages.");
        }

        _baseServer.Start();
    }