Exemplo n.º 1
0
        public WsHandler(string siteId)
        {
            _siteId = siteId;
            ConnectedChatClients = new WebSocketCollection();

            var timer = new Timer(DoWork, null, 5000, 1000);
        }
Exemplo n.º 2
0
            //覆寫OnOpen事件,鑄造新的ChatWebSocketHandler時觸發
            public override void OnOpen()
            {
                //判斷房間是否已在_chatRooms字典中,若沒有:新增一間房間;
                if (_chatRooms.ContainsKey(_roomID))
                {
                    _chatRooms[_roomID].Add(this);
                }
                else
                {
                    _chatRooms[_roomID] = new WebSocketCollection()
                    {
                        this
                    }
                };


                //用於確認連線狀態廣播的json
                Onlineobj obj = new Onlineobj()
                {
                    MemID = _toMemID
                };

                //確認聊天對象是否在線上
                if (_chatRooms[_roomID].Count > 1)
                {
                    obj.isOnline = true;
                }
                else
                {
                    obj.isOnline = false;
                }
                //將連線狀態廣播該房間
                _chatRooms[_roomID].Broadcast(JsonConvert.SerializeObject(obj, Formatting.Indented));
            }
Exemplo n.º 3
0
        public override void OnClose()
        {
            this.userID = this.WebSocketContext.QueryString["userID"];
            WebSocketCollection wsClients = (WebSocketCollection)HttpContext.Current.Application["WSClients"];

            wsClients.Remove(this);
            HttpContext.Current.Application["WSClients"] = wsClients;
        }
Exemplo n.º 4
0
        public WebSockets(string chaveAcesso)
        {
            _chaveAcesso = chaveAcesso;
            _settings    = ConfigurarSerializacao();

            if (webSocketClient == null)
            {
                webSocketClient = new WebSocketCollection();
            }
        }
Exemplo n.º 5
0
    public static WebSocketCollection ToCollection(this IEnumerable <WebSocketHandler> handlers)
    {
        var collection = new WebSocketCollection();

        foreach (var item in handlers)
        {
            collection.Add(item);
        }
        return(collection);
    }
Exemplo n.º 6
0
        /// <summary>
        /// Closes any WebSocket connections for a give userID
        /// </summary>
        /// <param name="userID">The userID to close connections for</param>
        private void closeWsConnections(string userID)
        {
            WebSocketCollection wsClients = (WebSocketCollection)HttpContext.Current.Application["WSClients"];

            List <WebSocketHandler> filtered = wsClients.Where(r => ((GameAccessWebSocketHandler)r).userID == userID).ToList();

            foreach (WebSocketHandler h in filtered)
            {
                h.Close();
            }
        }
Exemplo n.º 7
0
        public static void BroadcastExcept(this WebSocketCollection ws, WebSocketCollection collection, ChatUser user, string message)
        {
            WebSocketCollection tempCollection = new WebSocketCollection();

            foreach (ChatSocket item in collection)
            {
                if (!item.user.Username.Equals(user.Username))
                {
                    tempCollection.Add(item);
                }
            }
            tempCollection.Broadcast(message);
        }
Exemplo n.º 8
0
        public void Disconnect()
        {
            // Arrange
            ChatController      chatController = new ChatController();
            WebSocketCollection chatUser       = new WebSocketCollection();
            ChatService         chatHandler    = new ChatService("amay");

            chatUser.Add(chatHandler);

            // Action
            chatHandler.OnClose();

            // Result
            Assert.True(chatHandler.GetDisconnectStatus());
        }
Exemplo n.º 9
0
 //覆寫OnOpen事件,鑄造新的ChatWebSocketHandler時觸發
 public override void OnOpen()
 {
     //如果從teamID能找到對應的WebSocketCollection(也就是房間)則加入,否則新開一間房
     if (_chatRooms.ContainsKey(_roomKey))
     {
         _chatRooms[_roomKey].Add(this);
     }
     else
     {
         _chatRooms[_roomKey] = new WebSocketCollection()
         {
             this
         }
     };
 }
Exemplo n.º 10
0
        public void SendMessage()
        {
            // Arrange
            ChatController      chatController = new ChatController();
            WebSocketCollection chatUser       = new WebSocketCollection();
            ChatService         chatHandler    = new ChatService("amay");
            var serialization = new JavaScriptSerializer();

            chatUser.Add(chatHandler);
            var Jmsg = "{\"Username\":\"rblue\",\"MessageContent\":\"this is send test\"}";

            // Action
            chatHandler.OnMessage(Jmsg);

            // Result
            Assert.True(chatHandler.GetSendStatus());
        }
Exemplo n.º 11
0
        public override void OnOpen()
        {
            this.userID = this.WebSocketContext.QueryString["userID"];

            WebSocketCollection wsClients = (WebSocketCollection)HttpContext.Current.Application["WSClients"];

            wsClients.Add(this);
            HttpContext.Current.Application["WSClients"] = wsClients;
            string loginResponse = new SlackMUDRPG.CommandClasses.SlackMud().Login(this.userID, false, null, "WS");

            if (loginResponse == null)
            {
                this.Send("Character not found?");
            }
            else if (loginResponse != "")
            {
                this.Send(loginResponse);
                new SMCommandUtility(this.userID).InitateCommand("look");
            }
            ;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Returns User List With Json Format
        /// </summary>
        /// <param name="clientcollection"></param>
        /// <returns></returns>
        public string GetConnectedUserListJson(WebSocketCollection clientcollection)
        {
            string connectedUserListJsonStr = "";

            try
            {
                List <UserModel> connectedUserList = new List <UserModel>();
                foreach (var item in clientcollection)
                {
                    UserModel newUser = new UserModel();
                    newUser.UserName = item.WebSocketContext.QueryString["UserName"].ToString();
                    newUser.UserLogo = "1";
                    connectedUserList.Add(newUser);
                }
                connectedUserListJsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(connectedUserList);
            }
            catch (Exception ex)
            {
                connectedUserListJsonStr = "-1";
            }
            return(connectedUserListJsonStr);
        }
Exemplo n.º 13
0
 public HostedGame(GameConfiguration config)
 {
     this.config = config;
     clients     = new WebSocketCollection <GameService>();
     game        = new Game(config.BoardWidth, config.BoardHeight);
 }
Exemplo n.º 14
0
 static MyAppWebSocketHandler()
 {
     _connectedChatClients = new WebSocketCollection();
 }
Exemplo n.º 15
0
        static PoolWebSocket()
        {
            clients = new WebSocketCollection();

            Task.Run(() => UpdateTime());
        }
Exemplo n.º 16
0
        //private string name;

        public TrainingWebSocketHandler()
        {
            this.ownClient = new WebSocketCollection();
        }
 public static void AddSocket(string siteId, WebSocketCollection socketCollection)
 {
     _sockets.TryAdd(siteId, socketCollection);
 }
 public static string GetId(WebSocketCollection socket)
 {
     return(_sockets.FirstOrDefault(p => p.Value == socket).Key);
 }
Exemplo n.º 19
0
        public static void SendMessage(string serviceType, string nameOfHook, string messageContent, string botName, string channelOrPersonTo, string responseURL = null)
        {
            if (serviceType != null)
            {
                if (serviceType.ToLower() == "slack")
                {
                    messageContent = GetFormattedMessage("slack", messageContent);

                    using (WebClient client = new WebClient())
                    {
                        SlackClient sclient;

                        if ((responseURL != null) && (responseURL != ""))
                        {
                            sclient = new SlackClient(responseURL);
                        }
                        else
                        {
                            string urlWithAccessToken = GetAccessToken(serviceType, nameOfHook);
                            sclient = new SlackClient(urlWithAccessToken);
                        }

                        sclient.PostMessage(username: botName,
                                            text: messageContent,
                                            channel: channelOrPersonTo);
                    }
                }
                else if (serviceType.ToLower() == "ws")
                {
                    messageContent = GetFormattedMessage("html", messageContent);

                    WebSocketCollection wsClients = (WebSocketCollection)HttpContext.Current.Application["WSClients"];

                    List <WebSocketHandler> filtered = wsClients.Where(r => ((GameAccessWebSocketHandler)r).userID == channelOrPersonTo).ToList();

                    foreach (WebSocketHandler h in filtered)
                    {
                        h.Send(messageContent);
                    }
                }

                /*else if (serviceType.ToLower() == "bc")
                 * {
                 *      List<BotClient> botClients = (List<BotClient>)HttpContext.Current.Application["BotClients"];
                 *      BotClient bc = botClients.FirstOrDefault(bot => bot.UserID == channelOrPersonTo);
                 *      if (bc != null)
                 *      {
                 * string formatType = "skype";
                 * if (bc.ChannelType.ToLower() == "skype")
                 * {
                 * formatType = "skype";
                 * }
                 * else if (bc.ChannelType.ToLower() == "slack")
                 * {
                 * formatType = "slack";
                 * }
                 *
                 * messageContent = GetFormattedMessage(formatType, messageContent);
                 *
                 * BotClientUtility.SendMessage(bc, messageContent);
                 *      }
                 * }*/
            }
        }
Exemplo n.º 20
0
        protected void Application_Start(object sender, EventArgs e)
        {
            // Rebuild the char names list json
            new SMAccountHelper().RebuildCharacterJSONFile();

            // Websocket
            WebSocketCollection wsClients = new WebSocketCollection();

            Application["WSClients"] = wsClients;

            // Botclients
            //List<BotClient> botClients = new List<BotClient>();
            //Application["BotClients"] = botClients;

            // Character List
            List <SMCharacter> smc = new List <SMCharacter>();

            Application["SMCharacters"] = smc;

            // Room List
            List <SMRoom> smr = new List <SMRoom>();

            Application["SMRooms"] = smr;

            // Load the Commands into memory for usage later
            // Used for both parsing commands sent in and also for help output
            List <SMCommand> smcl = new List <SMCommand>();

            // Get all files from the Commands path
            string        commandsFolderPath = FilePathSystem.GetFilePathFromFolder("Commands");
            DirectoryInfo dirInfo            = new DirectoryInfo(commandsFolderPath);

            FileInfo[] CommandFiles = dirInfo.GetFiles("Commands.*.json");

            foreach (FileInfo file in CommandFiles)
            {
                string path = FilePathSystem.GetFilePath("Commands", file.Name, "");
                // Use a stream reader to read the file in (based on the path)
                using (StreamReader r = new StreamReader(path))
                {
                    // Create a new JSON string to be used...
                    string json = r.ReadToEnd();

                    // Get all the commands from the commands file
                    smcl.AddRange(JsonConvert.DeserializeObject <List <SMCommand> >(json));
                }
            }

            Application["SMCommands"] = smcl;

            // Load class builder specs into memory for usage later
            // Used for creating objects that are used to call user commands on
            ClassBuilderSpecs cbs       = new ClassBuilderSpecs();
            string            specsPath = FilePathSystem.GetFilePath("Misc", "ClassBuilder");

            if (File.Exists(specsPath))
            {
                using (StreamReader r = new StreamReader(specsPath))
                {
                    string json = r.ReadToEnd();

                    cbs = JsonConvert.DeserializeObject <ClassBuilderSpecs>(json);
                }
            }

            Application["ClassBuilderSpecs"] = cbs;

            // Load the Skills into memory for usage later
            // Used for both parsing commands sent in and also for help output
            List <SMSkill> lsk = new List <SMSkill>();

            // Get all filenames from path
            string        skillFolderFilePath = FilePathSystem.GetFilePathFromFolder("Skills");
            DirectoryInfo d = new DirectoryInfo(skillFolderFilePath);            //Assuming Test is your Folder

            FileInfo[] Files = d.GetFiles();
            foreach (FileInfo file in Files)
            {
                string skillFilePath = FilePathSystem.GetFilePath("Skills", file.Name, "");
                // Use a stream reader to read the file in (based on the path)
                using (StreamReader r = new StreamReader(skillFilePath))
                {
                    // Create a new JSON string to be used...
                    string json = r.ReadToEnd();

                    // ... get the information from the help file
                    lsk.Add(JsonConvert.DeserializeObject <SMSkill>(json));
                }
            }

            Application["SMSkills"] = lsk;

            // Load the Receipes into memory for usage later
            // Used for both parsing commands sent in and also for help output
            List <SMReceipe> smrl = new List <SMReceipe>();

            // Get all filenames from path
            string receipeFolderFilePath = FilePathSystem.GetFilePathFromFolder("Receipe");

            d     = new DirectoryInfo(receipeFolderFilePath);        //Assuming Test is your Folder
            Files = d.GetFiles();
            foreach (FileInfo file in Files)
            {
                string receipeFilePath = FilePathSystem.GetFilePath("Receipe", file.Name, "");
                // Use a stream reader to read the file in (based on the path)
                using (StreamReader r = new StreamReader(receipeFilePath))
                {
                    // Create a new JSON string to be used...
                    string json = r.ReadToEnd();

                    // ... get the information from the help file
                    smrl.Add(JsonConvert.DeserializeObject <SMReceipe>(json));
                }
            }

            Application["SMReceipes"] = smrl;

            // Load the Skills into memory for usage later
            // Used for both parsing commands sent in and also for help output
            List <SMNPC> lnpcs = new List <SMNPC>();

            //Get all filenames from path

            string NPCsFolderFilePath = FilePathSystem.GetFilePathFromFolder("NPCs");

            d     = new DirectoryInfo(NPCsFolderFilePath);        //Assuming Test is your Folder
            Files = d.GetFiles();
            foreach (FileInfo file in Files)
            {
                if (file.Name != "NPCNamesList.json")
                {
                    string NPCFilePath = FilePathSystem.GetFilePath("NPCs", file.Name, "");
                    // Use a stream reader to read the file in (based on the path)
                    using (StreamReader r = new StreamReader(NPCFilePath))
                    {
                        // Create a new JSON string to be used...
                        string json = r.ReadToEnd();

                        // ... get the information from the help file
                        lnpcs.Add(JsonConvert.DeserializeObject <SMNPC>(json));
                    }
                }
            }

            Application["SMNPCs"] = lnpcs;

            // load and fetch NPCRaces, using a dictionary for speedy lookups later.
            Dictionary <string, NPCRace> dnpcRaces = new Dictionary <string, NPCRace>();

            string NPCRacesFolderFilePath = FilePathSystem.GetFilePathFromFolder("NPCRaces");

            d     = new DirectoryInfo(NPCRacesFolderFilePath);
            Files = d.GetFiles();
            foreach (FileInfo file in Files)
            {
                string RaceFilePath = FilePathSystem.GetFilePath("NPCRaces", file.Name, "");
                using (StreamReader r = new StreamReader(RaceFilePath))
                {
                    string  json         = r.ReadToEnd();
                    NPCRace raceFromJSON = JsonConvert.DeserializeObject <NPCRace>(json);
                    dnpcRaces[raceFromJSON.Name.ToLower()] = raceFromJSON;
                }
            }

            Application["NPCRaces"] = dnpcRaces;

            Application["Parties"] = new List <SMParty>();

            #region "The Pulse"

            // Set the current context to pass into the thread
            HttpContext ctx = HttpContext.Current;

            // Create a new thread
            Thread pulse = new Thread(new ThreadStart(() =>
            {
                HttpContext.Current = ctx;
                new SMPulse().Initiate();                 // this is the item that is going to initiate
            }));

            // Start the thread
            pulse.Start();

            #endregion

            // Register the global configuration items for the bot helper
            //GlobalConfiguration.Configure(WebAPIConfig.Register);
        }
Exemplo n.º 21
0
 public HostedGame(GameConfiguration config)
 {
     this.config = config;
     clients = new WebSocketCollection<GameWebSocketService>();
     game = new PushFrenzy.Rules.Game(config.BoardWidth, config.BoardHeight);
 }
Exemplo n.º 22
0
 static Socket()
 {
     Clients = new WebSocketCollection();
 }
Exemplo n.º 23
0
 static ManipuladorChat()
 {
     Clientes = new WebSocketCollection();
 }