Contains the event data associated with a WebSocket.OnMessage event.

A WebSocket.OnMessage event occurs when the WebSocket receives a text or binary message, or a Ping if the WebSocket.EmitOnPing property is set to true.

If you would like to get the message data, you should access the Data or RawData property.

Inheritance: System.EventArgs
Beispiel #1
0
    public void gotMessage(object sender, WebSocketSharp.MessageEventArgs msg)
    {
        if (msg.Type == WebSocketSharp.Opcode.Binary)
        {
            lock (updateLock) {
                updateMsg.ClearVrmsg();
                updateMsg.MergeFrom(new Google.Protobuf.CodedInputStream(msg.RawData));
                Google.Protobuf.VRCom.Update.VrmsgOneofCase msgType = updateMsg.VrmsgCase;
                switch (msgType)
                {
                case Google.Protobuf.VRCom.Update.VrmsgOneofCase.Mocap:
                    mocapMsg = updateMsg;
                    break;

                case Google.Protobuf.VRCom.Update.VrmsgOneofCase.Hydra:
                    hydraMsg = updateMsg;
                    break;

                case Google.Protobuf.VRCom.Update.VrmsgOneofCase.Wiimote:
                    wiimoteMsgs.Enqueue(updateMsg.Clone());
                    break;

                default:
                    Debug.Log("Received an unknown or empty message");
                    break;
                }
            }
        }
        else
        {
            //jmsg = JsonUtility.FromJson (msg.Data);
            Debug.Log(msg.Data);
        }
    }
        protected override void OnMessage(MessageEventArgs e)
        {
            string msg = string.Empty;
            string logMsg = string.Empty;

            // grab first part of request
            // everything before the first _ denotes what method should be called... maybe not very clean...
            List<string> parameters = e.Data.Split('_').ToList();
            string requestType = parameters[0];
            // we've already gotten the requestType, now remove it, so we don't have to work around it
            parameters.RemoveAt(0);

            switch (requestType)
            {
                case "getMatchHistory":
                    Console.WriteLine("Received match history request for: " + parameters[0]);
                    msg = GetMatchHistory(parameters[0]);
                    logMsg = "Sent match history response.";
                    break;

                default:
                    Console.WriteLine("An unknown request was made.");
                    break;
            }

            Send(msg);
            Console.WriteLine(logMsg);
        }
Beispiel #3
0
        protected override void OnMessage(MessageEventArgs e)
        {
            dynamic json = JsonConvert.DeserializeObject<dynamic>(e.Data);
            int type;
            try
            {
                type = Convert.ToInt16(json.type);
            }
            catch
            {
                return;
            }

            switch (type)
            {
                case 0:
                    ProcessLogin(JsonConvert.DeserializeObject<LoginRequest>(e.Data));
                    break;
                case 1:
                    ProcessCommand(JsonConvert.DeserializeObject<CommandRequest>(e.Data));
                    break;
                case 4:
                    GetBans(JsonConvert.DeserializeObject<BanListRequest>(e.Data));
                    break;
                case 5:
                    GetBEClients(JsonConvert.DeserializeObject<ClientListRequest>(e.Data));
                    break;
            }
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }

            log.Info("Received message: \"" + e.Data + "\" of type \"" + e.Type.ToString() + "\"");

            if (string.IsNullOrEmpty(e.Data))
                return;

            using (var session = Bootstrapper.CreateSession())
            using (var transaction = session.BeginTransaction())
            {
                bool commitTransaction = HandleMessage(session, e.Data, (string message) =>
                {
                    log.Info("Sending message: " + message);
                    Send(message);
                });

                if (commitTransaction)
                    transaction.Commit();
                else
                    transaction.Rollback();
            }
        }
Beispiel #5
0
        private void Client_Message(MessageEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke((MethodInvoker)delegate {
                    Client_Message(e);
                });
                return;
            }

            outputText.AppendText(string.Format("Message Received on {0}:{1}",
                DateTime.Now, Environment.NewLine));

            if (e.IsBinary)
            {
                outputText.Append(e.RawData, e.RawData.Length);
            }
            else
            {
                outputText.AppendText(e.Data);
            }

            outputText.AppendText(Environment.NewLine);
            outputText.AppendText(Environment.NewLine);
        }
Beispiel #6
0
 public static void client_OnMessage(object sender, MessageEventArgs e)
 {
     string msg = e.Data;
     Debug.WriteLine(string.Format("wsGPS OnMessage => {0}", msg));
     //�����������Ҫ��ԭʼ����Ӧ�ñ�������֮����Ч��������ͻ���
     services.get_service(registe_name).Send(msg);
 }
        protected override void OnMessage(MessageEventArgs e)
        {
            dynamic request = new JavaScriptSerializer().Deserialize(e.Data, typeof(object));

            switch ((string)request.action)
            {
                case "start":
                   json = new JavaScriptSerializer().Serialize(true);
                   Telemetry.Game.StartRecording();
                    break;

                case "stop":
                    Telemetry.Game.StopRecording();
                    json = new JavaScriptSerializer().Serialize(true);
                    break;

                case "analyse":
                    Telemetry.Game.AnalyseRecordingForTracks();
                 //   json = new JavaScriptSerializer().Serialize(GameState.TrackAnalysis);
                    break;

                case "loadanalysedtrack":
                    Track track = Telemetry.Game.BuildTrackData(request.name, request.lap);
                    json = new JavaScriptSerializer().Serialize(track);
                    break;

            }

            Send(json);
        }
 protected override void OnMessage(MessageEventArgs e)
 {
     WSGroupServices.GetLogger().Info("Message received");
     try
     {
         var message = spp.Parse(e.Data);
         if (message is Pull)
         {
             PullHandler();
         }
         else if (message is Push)
         {
             PushHandler((Push)message);
         }
         else if (message is Register)
         {
             RegisterHandler((Register)message);
         }
         else { WSGroupServices.GetLogger().Error("Unhandled message type"); }
     }
     catch (ServerProtocolParsingError)
     {
         WSGroupServices.GetLogger().Error("Message parsing error:\n" + e.Data.Substring(0, 200));
     }
 }
        private void OnRecievedMessage(object sender, MessageEventArgs message)
        {
            var result = BuildResult.Parse(message.Data);
            var msg = result.ToMessage();

            if (result.IsFailure)
            {
                ShowBalloon(ToolTipIcon.Info, msg);
                PlaySound(result);
                return;
            }

            if (Settings.Default.ShowErrorOnly)
            {
                return;
            }

            if (result.IsSuccess)
            {
                ShowBalloon(ToolTipIcon.Info, msg);
                PlaySound(result);
            }
            else if (result.IsUnstable)
            {
                ShowBalloon(ToolTipIcon.Warning, msg);
                PlaySound(result);
            }
            else if (result.IsAborted)
            {
                ShowBalloon(ToolTipIcon.Info, msg);
                PlaySound(result);
            }
        }
Beispiel #10
0
 protected override void OnMessage(MessageEventArgs e)
 {
     try
     {
         switch (e.Type)
         {
             case Opcode.TEXT:
                 {
                     JArray dcode = JArray.Parse(e.Data);
                     ClientOpcode opcode = (ClientOpcode)int.Parse(dcode[0].ToString());
                     LogConsole.Show(LogType.DEBUG, "opcode: {0}", opcode);
                     Program.PacketsManager.ProcessBytes(_session, ref dcode);
                     break;
                 }
             default:
                 {
                     break;
                 }
         }
     }
     catch (Exception Ex)
     { 
         LogConsole.Show(LogType.ERROR, "{0}", Ex.ToString());
     }
 }
 private void SocketMessage(object sender, WebSocketSharp.MessageEventArgs e)
 {
     if (e != null)
     {
         if (e.IsPing)
         {
             Debug.Log("Socket Receive PING ");
         }
         else if (e.IsText)
         {
             Debug.Log("[New Message Text]");
             if (!ParseMessage(e.Data))
             {
                 Debug.Log("Unparse Message : " + e.Data);
             }
         }
         else if (e.IsBinary)
         {
             Debug.Log("Socket Receive Binary ");
         }
         else
         {
             Debug.Log("Socket Receive Unknow ");
         }
     }
 }
        protected override void OnMessage(MessageEventArgs e)
        {
            log.Info("Received message: " + e.Data);

            if (string.IsNullOrEmpty(e.Data))
                return;

            var msg = JsonConvert.DeserializeObject<Message>(e.Data);

            if (msg == null || string.IsNullOrEmpty(msg.Path) || _servicesDict[msg.Path] == null)
                return;

            var session = Bootstrapper.CreateSession();
            using (var transaction = session.BeginTransaction()) {
                bool commitTransaction = true;

                _servicesDict[msg.Path].HandleMessage(session, e.Data, (string message) => {
                    log.Info("Sending message: " + message);
                    Send(message);
                }, ref commitTransaction);

                if (commitTransaction)
                    transaction.Commit();
                else
                    transaction.Rollback();
            }
        }
Beispiel #13
0
 protected override void OnMessage(MessageEventArgs e)
 {
     var msg = QueryString.Contains("name")
       ? String.Format("'{0}' returns to {1}", e.Data, QueryString["name"])
       : e.Data;
       Send(msg);
 }
Beispiel #14
0
 protected override void OnMessage(MessageEventArgs e) {
   string[] sa;
   if(e.Type==Opcode.Text && !string.IsNullOrEmpty(e.Data) && (sa=e.Data.Split('\t'))!=null && sa.Length>0) {
     if(_verbose.value) {
       X13.Log.Debug("ws.msg({0})", string.Join(", ", sa));
     }
     if(sa[0]=="C" && sa.Length==3) {  // Connect, username, password
       if((sa[1]!="local" || _ses.ip.IsLocal()) && MQTT.MqBroker.CheckAuth(sa[1], sa[2])) {
         _ses.userName=sa[1];
         Send("C\ttrue");
         if(_verbose.value) {
           X13.Log.Info("{0} logon as {1} success", _ses.owner.name, _ses.ToString());
         }
       } else {
         Send("C\tfalse");
         if(_verbose.value) {
           X13.Log.Warning("{0}@{2} logon  as {1} failed", _ses.owner.name, sa[1], _ses.owner.value);
         }
         Sessions.CloseSession(base.ID);
       }
     } else if(!_disAnonym.value || (_ses!=null && !string.IsNullOrEmpty(_ses.userName))) {
       if(sa[0]=="P" && sa.Length==3) {
         HttpWsPl.ProcessPublish(sa[1], sa[2], _ses);
       } else if(sa[0]=="S" && sa.Length==2) {
         _subscriptions.Add(Topic.root.Subscribe(sa[1], SubChanged));
       }
     }
   }
 }
Beispiel #15
0
    private void OnReceiveResponse(object sender, WebSocketSharp.MessageEventArgs e)
    {
        CommandResponse c;

        try {
            c = JsonUtility.FromJson <CommandResponse> (e.Data);
        } catch (NullReferenceException) {
            Debug.LogWarning("Wrong Command Response serialization");
            c = null;
        }

        if (c == null)
        {
            return;
        }

        switch (c.action)
        {
        case CommandAction.UPDATE_PLAYERS:
            this.OnUpdatePlayerCommandAction(c);
            break;

        case CommandAction.START_GAME:
            this.OnStartGameCommandAction(c);
            break;

        default:
            Debug.LogError("NOT IMPLEMENTED: CommandAction not implemented");
            break;
        }
    }
 private void OnMessage(object sender, MessageEventArgs e)
 {
     IService service = e.CallerContext as IService;
     service.ServiceManager.Get<ISemanticProcessor>().ProcessInstance<SocketMembrane, ClientSocketMessage>(msg =>
         {
             msg.Text = e.Data;
         });
 }
 private void OnMessageAdv(object sender, MessageEventArgs e)
 {
     JObject body = JObject.Parse(e.Data);
     if (body["msg"] == null)
         return;
     string msg = body["msg"].ToObject<string>();
     DdpMessage?.Invoke(this, new DdpMessage(msg, e.Data));
 }
Beispiel #18
0
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine("Message received: " + e.Data);
            var msg = e.Data == "HELLO"
                      ? "Nya"
                      : "Pff";

            Send(msg);
        }
        void OnMessageInternal(object sender, MessageEventArgs e)
        {
            Debug.Assert(e.Type == Opcode.Text);

            if (OnMessage != null)
            {
                OnMessage(this, UTF8Encoding.UTF8.GetString(e.RawData));
            }
        }
 private void OnSocketMessage(object sender, MessageEventArgs e)
 {
     dynamic message = JsonConvert.DeserializeObject(e.Data);
     if (message.type == "message")
     {
         Log.Write("Recieved message: " + e.Data);
         _rtmIncomingMessages.OnMessage(message);
     }
 }
Beispiel #21
0
        protected override void OnMessage(MessageEventArgs e)
        {
            var name = Context.QueryString ["name"];
              var msg = name != null
              ? String.Format ("Returns '{0}' to {1}", e.Data, name)
              : e.Data;

              Send (msg);
        }
 protected override void OnMessage(MessageEventArgs e)
 {
     IService service = e.CallerContext as IService;
     service.ServiceManager.Get<ISemanticProcessor>().ProcessInstance<SocketMembrane, ServerSocketMessage>(msg =>
         {
             msg.Text = e.Data;
             msg.Session = this;
         });
 }
Beispiel #23
0
 public string RecvString()
 {
     WebSocketSharp.MessageEventArgs retval = Recv();
     if (retval == null)
     {
         return(null);
     }
     return(Encoding.UTF8.GetString(retval.RawData));
 }
Beispiel #24
0
        protected override void OnMessage(MessageEventArgs e)
        {
            var name = Context.QueryString ["name"];
              var msg = !name.IsNullOrEmpty ()
                ? String.Format ("'{0}' to {1}", e.Data, name)
                : e.Data;

              Send (msg);
        }
Beispiel #25
0
 public async void ServerToClientOnMessage(object sender, MessageEventArgs e)
 {
     Task<JSonPacket> PacketTask = JsonConvert.DeserializeObjectAsync<JSonPacket>(e.Data);
     JSonPacket ReceivePacket = await PacketTask;
     
     if (ReceivePacket.Protocol == "request_login")
         request_login_OK(ReceivePacket);
     else if (ReceivePacket.Protocol == "request_chat")
         request_chat_OK(ReceivePacket);
 }
Beispiel #26
0
        protected override void OnMessage(object sender, MessageEventArgs e)
        {
            var msg = e.Data;
            Console.WriteLine(string.Format("OnMessage => {0}", msg));
            Send("echo -> " + msg);

            //var msg = QueryString.Exists("name")
            //        ? String.Format("'{0}' returns to {1}", e.Data, QueryString["name"])
            //        : e.Data;
        }
        protected override void OnMessage(MessageEventArgs e)
        {

            data = JsonConvert.DeserializeObject(e.Data);
            payload = this.data.Payload;
            type = this.data.Type;

            // TODO: Check payload integrity, missing elements causes crash


            switch ((int)data.Type)

            if (type != (int)GENERAL.LOGIN || type != (int)GENERAL.HEARTBEAT)
                if (!Authenticate(this)) return;

            switch ((GameType)type)

            {
                // GAME LOGIC REQUESTS
                case GameType.QUEUE:
                    engine.QueuePlayer(OnlinePlayers[this]);
                    break;

                    case GameType.ATTACK:
                    engine.RequestCardAttack(data.Payload);
                    break;

                case GameType.USECARD:
                    engine.RequestUseCard(OnlinePlayers[this]);
                    break;

                case GameType.NEXTROUND:
                    engine.RequestNextRound(data.Payload);
                    break;
                case GameType.MOVE_CARD:
                       engine.MovedCard(OnlinePlayers[this]);
                    break;
            }

            switch ((GENERAL)type)
            {
                case GENERAL.LOGIN:
                    this.Login();
                    break;

                case GENERAL.LOGOUT:
                    this.Logout();
                    break;

                case GENERAL.HEARTBEAT:
                    this.HeartBeat();
                    break;
            }
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            if (e.Type != Opcode.Text) return;

            try {
                var obj = JObject.Parse(e.Data);
                OnMessage((String) obj["type"], obj["data"]);
            } catch (Exception ex) {
                Send("error", FormatError(ex));
            }
        }
 private void OnMessage(object sender, MessageEventArgs e)
 {
     if (ReceivedMessage != null)
     {
         var extendedByteArray = CreateExtendedByteArray(e.RawData);
         var decompressed = mDecompressor.Decompress(extendedByteArray);
         var decoded = mDecoder.Decode(decompressed);
         var decodedMessageEventArgs = new DecodedMessageEventArgs(decoded);
         ReceivedMessage(sender, e);
     }
 }
Beispiel #30
0
        protected override void OnMessage(MessageEventArgs e)
        {
            dynamic message = JsonConvert.DeserializeObject(e.Data);

            if (message.requestTypeId == RequestTypes.RegisterUser)
            {
                nameList.Add(this.ID, message.username.ToString());
                SendMessage("System", $"{message.username} just connected");
            }
            else
                SendMessage(nameList[this.ID], message.message.ToString());
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            var msg = e.Data;
            if (msg == "subscribe") {
                /* Do a full synchronization and subscribe the client to periodical updates*/
                core.Synchronize (this);
                core.Subscribe (this);

            } else {
                Send ("Unknown request");
            }
        }
Beispiel #32
0
 private void OnMessage(object sender, WebSocketSharp.MessageEventArgs args)
 {
     if (_pendingTasks.Count > 0)
     {
         var completion = _pendingTasks.Dequeue();
         completion.TrySetResult(args.RawData);
     }
     else
     {
         _pendingMessages.Enqueue(args.RawData);
     }
 }
 protected override void OnMessage(MessageEventArgs e)
 {
     if (e.Type == Opcode.Close) {
         lock (s_lockObj) {
             if (s_accPtClients.ContainsKey (m_accPtClientID)) {
                 s_accPtClients.Remove (m_accPtClientID);
             }
         }
     } else {
         var res = DispatchMessage (e);
         Send (res);
     }
 }
Beispiel #34
0
    public JsonData GetResponseJsonData()
    {
        WebSocketSharp.MessageEventArgs e = hs.MessageRepsonseEvent;
        if (e == null)
        {
            return(null);
        }

        JsonData jsonData = JsonMapper.ToObject(e.Data);

        //jsonObject.bClassNameExist = false;
        return(jsonData);
    }
Beispiel #35
0
    protected override void OnMessageDequeue(WSServiceBehaviour beh, WebSocketSharp.MessageEventArgs message)
    {
        OSCPacket oscpacket = OSCPacket.Unpack(message.RawData);

        if (oscpacket != null)
        {
            OnOSCMessage(oscpacket as OSCMessage, beh);
        }
        else
        {
            DebugService("unpacking osc messge failed " + message.Data);
        }
    }
Beispiel #36
0
 protected override void OnMessage(object sender, MessageEventArgs e)
 {
     var msg = e.Data;
     Debug.WriteLine(string.Format("GPS OnMessage => {0}", msg));
     //Send("echo -> " + msg);
     try
     {
         command cmd = (command)JsonConvert.DeserializeObject(msg, typeof(command));
         Debug.WriteLine(cmd.print_string());
     }
     catch
     {
         Debug.WriteLine("parse error!");
     }
     services.add_log(GPS.raw_data_parser(msg));
 }
        protected override void OnMessage(MessageEventArgs e)
        {
            string msg = string.Empty;
            string logMsg = string.Empty;

            // grab first part of request
            // everything before the first _ denotes what method should be called... maybe not very clean...
            List<string> parameters = e.Data.Split('_').ToList();
            string requestType = parameters[0];
            // we've already gotten the requestType, now remove it, so we don't have to work around it
            parameters.RemoveAt(0);

            switch (requestType)
            {

            }
        }
Beispiel #38
0
    /// <summary>
    /// Raises the message event.
    /// uniform asyncronzilly interface, call-back...
    /// </summary>
    /// <param name="sender">Sender.</param>
    /// <param name="e">E.</param>
    protected void OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
    {
                #if SOCKET_IO_DEBUG
        debugMethod.Invoke("[SocketIO] Raw message: " + e.Data);
                #endif
        Debug.Log("[SocketIO] OnMessage e.Data: " + e.Data);
        hs.MessageRepsonseEvent = null;
        hs.IsSyncHttpDone       = true;

        //for to unserizlized
        JsonData _jsonObect = JsonMapper.ToObject(e.Data);
        if (null == _jsonObect)
        {
            Log.error("NetWorkManager", "OnMessage#################null == _jsonObect!");
            return;
        }

        /*
         *              Packet packet = decoder.Decode(e);*/
        //直接构造DangmuViewDataConveter...
        //目前无法区分消息类型....
        DangmuTextRsp textRsp = new DangmuTextRsp();
        if (false == textRsp.ParseJsonObject(_jsonObect))
        {
            Log.error("NetWorkManager", "OnMessage#################ParseJsonObject failed!");
            return;
        }

        if (textRsp.dataList.Count <= 0)
        {
            Log.debug("NetWorkManager", "OnMessage#################No new message!");
            return;
        }

        foreach (DangmuTextRsp.DangmuTextData textData in textRsp.dataList)
        {
            DangmuViewDataConveter dataConv = new DangmuViewDataConveter(textData);

            //insert derectly....
            //SCMainWinController.Instance().DangmuControl.enqueueToDataQueue( dataConv );
        }

        //null to do...
    }
    protected override void OnMessageDequeue(WebSocketSharp.MessageEventArgs message)
    {
        // statsSumary.AddBytesRecieved(message.RawData.Length);
        OSCPacket oscpacket = OSCPacket.Unpack(message.RawData);

        if (oscpacket.Address == "/message")
        {
            DebugClient("recieved messaget " + oscpacket.GetString(0));
        }
        if (oscpacket != null)
        {
            OnOSCMessage(oscpacket as OSCMessage);
            //	DebugClient("recieved " + oscpacket.Address);
        }
        else
        {
            DebugClient("unpacking osc messge failed " + message.Data);
        }
    }
Beispiel #40
0
 protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
 {
     // Queue the OnMessage event to be called.
     if (webService != null)
     {
         if (e.IsText)
         { // Parse the data as a JSON object
             JSONObject json = new JSONObject(e.Data);
             webServer.TaskQueue.Enqueue(() => {
                 Debug.Log(e.Data);
                 webService.OnMessage(json);
             });
         }
         else if (e.IsBinary)
         { // Process the raw binary data
             webServer.TaskQueue.Enqueue(() => webService.OnData(e.RawData));
         }
     }
 }
Beispiel #41
0
    private void OnRecieveResponse(object sender, WebSocketSharp.MessageEventArgs e)
    {
        CommandResponse c;

        try
        {
            c = JsonUtility.FromJson <CommandResponse>(e.Data);
        }
        catch (NullReferenceException)
        {
            Debug.LogWarning("Wrong Command Response serialization");
            c = null;
        }

        if (c == null)
        {
            return;
        }

        // TODO: Manage server response
        Debug.Log(c);
    }
    private void OnServerCountReceive(object sender, WebSocketSharp.MessageEventArgs e)
    {
        CommandResponse c;

        try
        {
            c = JsonUtility.FromJson <CommandResponse>(e.Data);
            if (c.action != ServerCounter.ACTION_TO_OBEY)
            {
                return;
            }
            else
            {
                // TODO: Check that this is working.
                this.counting     = true;
                this.currentValue = float.Parse(c.payload);
            }
        }
        catch (NullReferenceException)
        {
            Debug.LogWarning("Wrong Command Response serialization");
            return;
        }
    }
Beispiel #43
0
 private void WsClient_OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
 {
     if (e.IsText)
     {
         string msg = e.Data;
         //Debug.Log(msg);
         try
         {
             //Debug.Log(msg);
             TouchEventData touchEvent = TouchEventData.ParseToucEventFromJsonString(msg);
             if (pointerReceivedListener != null)
             {
                 pointerReceivedListener(touchEvent);
             }
             gestureRecognizer.RecognizeGesture(touchEvent);
             //string decodedMsg = "From JSON: ";
             //decodedMsg += string.Format("Event type:{0};Pointers count: {1};AvaiPointers:{2}", touchEvent.EventType, touchEvent.PointerCount, touchEvent.AvaiPointers.Length);
         }
         catch (Exception ex)
         {
             Debug.Log("JSON Parsing Error:" + ex.Message);
         }
     }
 }
Beispiel #44
0
        private void SocketDataReceived(object sender, WebSocketSharp.MessageEventArgs result)
        {
            GatewayResponse payload = result.Data.Deserialize <GatewayResponse>();

            Sequence = payload.Sequence;

            try
            {
                switch (payload.Opcode)
                {
                case GatewayOpcode.Event:
                    /*
                     * Console.WriteLine(payload.Title);
                     *
                     * File.AppendAllText("Debug.log", $"{payload.Title}: {payload.Data}\n");*/

                    switch (payload.Title)
                    {
                    case "READY":
                        Login login = payload.DeserializeEx <Login>().SetClient(this);

                        this.User         = login.User;
                        this.UserSettings = login.Settings;
                        this.SessionId    = login.SessionId;

                        if (Config.Cache)
                        {
                            if (this.User.Type == DiscordUserType.User)
                            {
                                PrivateChannels = login.PrivateChannels;

                                foreach (var guild in login.Guilds)
                                {
                                    GuildCache.Add(guild.Id, guild.ToSocketGuild());
                                }

                                foreach (var notifSettings in login.ClientGuildSettings)
                                {
                                    if (notifSettings["guild_id"].Type == JTokenType.Null)
                                    {
                                        PrivateChannelSettings = notifSettings["channel_overrides"].ToObject <List <DiscordChannelSettings> >();
                                    }
                                    else
                                    {
                                        var settings = notifSettings.ToObject <ClientGuildSettings>().SetClient(this);

                                        GuildSettings.Add(settings.Guild.Id, settings);
                                    }
                                }
                            }
                            else
                            {
                                PrivateChannels.Clear();
                                GuildCache.Clear();
                                GuildSettings.Clear();
                            }
                        }

                        LoggedIn = true;

                        Task.Run(() => OnLoggedIn?.Invoke(this, new LoginEventArgs(login)));
                        break;

                    case "USER_SETTINGS_UPDATE":
                        if (UserSettings != null)         // for some reason this is null sometimes :thinking:
                        {
                            var update = payload.Deserialize <JObject>();

                            foreach (var field in UserSettings.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                            {
                                foreach (var attr in field.CustomAttributes)
                                {
                                    if (attr.AttributeType == typeof(JsonPropertyAttribute))
                                    {
                                        string propertyName = attr.ConstructorArguments[0].Value.ToString();

                                        if (update.ContainsKey(propertyName))
                                        {
                                            field.SetValue(UserSettings, update.GetValue(propertyName).ToObject(field.FieldType));
                                        }

                                        break;
                                    }
                                }
                            }

                            foreach (var property in UserSettings.GetType().GetProperties())
                            {
                                foreach (var attr in property.CustomAttributes)
                                {
                                    if (attr.AttributeType == typeof(JsonPropertyAttribute))
                                    {
                                        string propertyName = attr.ConstructorArguments[0].Value.ToString();

                                        if (update.ContainsKey(propertyName))
                                        {
                                            property.SetValue(UserSettings, update.GetValue(propertyName).ToObject(property.PropertyType));
                                        }

                                        break;
                                    }
                                }
                            }

                            Task.Run(() => OnSettingsUpdated?.Invoke(this, new DiscordSettingsEventArgs(UserSettings)));
                        }
                        break;

                    case "USER_GUILD_SETTINGS_UPDATE":
                        if (Config.Cache)
                        {
                            JObject obj = payload.Deserialize <JObject>();

                            if (obj["guild_id"].Type == JTokenType.Null)
                            {
                                PrivateChannelSettings = obj["channel_overrides"].ToObject <List <DiscordChannelSettings> >();
                            }
                            else
                            {
                                var settings = obj.ToObject <ClientGuildSettings>().SetClient(this);

                                GuildSettings[settings.Guild.Id] = settings;
                            }
                        }
                        break;

                    case "USER_UPDATE":
                        DiscordUser user = payload.Deserialize <DiscordUser>().SetClient(this);

                        if (user.Id == User.Id)
                        {
                            User.Update(user);
                        }

                        if (Config.Cache)
                        {
                            foreach (var dm in PrivateChannels)
                            {
                                bool updated = false;

                                foreach (var recipient in dm.Recipients)
                                {
                                    if (recipient.Id == user.Id)
                                    {
                                        recipient.Update(user);

                                        updated = true;

                                        break;
                                    }
                                }

                                if (updated)         // this is somewhat resource intensive, so let's reduce the uses as much as possible
                                {
                                    dm.UpdateSelfJson();
                                }
                            }
                        }

                        Task.Run(() => OnUserUpdated?.Invoke(this, new UserEventArgs(user)));
                        break;

                    case "GUILD_MEMBER_LIST_UPDATE":
                        var args = payload.Deserialize <GuildMemberListEventArgs>();

                        File.AppendAllText("Debug.log", $"{payload.Data}\n");

                        OnMemberListUpdate?.Invoke(this, args);
                        break;

                    case "GUILD_CREATE":
                    {
                        SocketGuild guild = payload.DeserializeEx <SocketGuild>().SetClient(this);

                        if (Config.Cache)
                        {
                            GuildCache.Remove(guild.Id);

                            GuildCache.Add(guild.Id, guild);
                        }

                        Task.Run(() => OnJoinedGuild?.Invoke(this, new SocketGuildEventArgs(guild, Lurking.HasValue && Lurking.Value == guild.Id)));
                    }
                    break;

                    case "GUILD_UPDATE":
                    {
                        DiscordGuild guild = payload.Deserialize <DiscordGuild>().SetClient(this);

                        if (Config.Cache)
                        {
                            GuildCache[guild].Update(guild);
                        }

                        Task.Run(() => OnGuildUpdated?.Invoke(this, new GuildEventArgs(guild)));
                    }
                    break;

                    case "GUILD_DELETE":
                    {
                        UnavailableGuild guild = payload.Deserialize <UnavailableGuild>();

                        if (Lurking.HasValue && Lurking.Value == guild.Id)
                        {
                            Lurking = null;
                        }

                        if (Config.Cache)
                        {
                            if (guild.Unavailable)
                            {
                                GuildCache[guild.Id].Unavailable = true;
                            }
                            else
                            {
                                GuildCache.Remove(guild.Id);
                            }

                            GuildSettings.Remove(guild.Id);
                        }

                        Task.Run(() => OnLeftGuild?.Invoke(this, new GuildUnavailableEventArgs(guild)));
                    }
                    break;

                    case "GUILD_MEMBER_ADD":
                        Task.Run(() => OnUserJoinedGuild?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMemberUpdate>().SetClient(this).Member)));
                        break;

                    case "GUILD_MEMBER_REMOVE":
                        Task.Run(() => OnUserLeftGuild?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMemberUpdate>().SetClient(this).Member)));
                        break;

                    case "GUILD_MEMBER_UPDATE":
                        Task.Run(() => OnGuildMemberUpdated?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMember>().SetClient(this))));
                        break;

                    case "GUILD_MEMBERS_CHUNK":
                        Task.Run(() => OnGuildMembersReceived?.Invoke(this, new GuildMembersEventArgs(payload.Deserialize <GuildMemberList>().SetClient(this))));
                        break;

                    case "GIFT_CODE_CREATE":
                        Task.Run(() => OnGiftCodeCreated?.Invoke(this, payload.Deserialize <GiftCodeCreatedEventArgs>()));
                        break;

                    case "PRESENCE_UPDATE":
                        Task.Run(() => OnUserPresenceUpdated?.Invoke(this, new PresenceUpdatedEventArgs(payload.Deserialize <DiscordPresence>().SetClient(this))));
                        break;

                    case "VOICE_STATE_UPDATE":
                        DiscordVoiceState newState = payload.Deserialize <DiscordVoiceState>().SetClient(this);

                        // TODO: figure out how the client gets the initial voice states

                        if (Config.Cache)
                        {
                            List <DiscordVoiceState> voiceStates;

                            if (newState.Guild == null)
                            {
                                voiceStates = PrivateVoiceStates[newState.Channel.Id];
                            }
                            else
                            {
                                voiceStates = GuildCache[newState.Guild]._voiceStates;
                            }

                            int i = voiceStates.FindIndex(s => s.UserId == newState.UserId);

                            if (i > -1)
                            {
                                voiceStates[i] = newState;
                            }
                            else
                            {
                                voiceStates.Add(newState);
                            }
                        }

                        Task.Run(() => OnVoiceStateUpdated?.Invoke(this, new VoiceStateEventArgs(newState)));
                        break;

                    case "VOICE_SERVER_UPDATE":
                        Task.Run(() => OnVoiceServer?.Invoke(this, payload.Deserialize <DiscordVoiceServer>()));
                        break;

                    case "GUILD_ROLE_CREATE":
                    {
                        DiscordRole role = payload.Deserialize <RoleUpdate>().Role.SetClient(this);

                        if (Config.Cache)
                        {
                            GuildCache[role.GuildId]._roles.Add(role);
                        }

                        Task.Run(() => OnRoleCreated?.Invoke(this, new RoleEventArgs(role)));
                    }
                    break;

                    case "GUILD_ROLE_UPDATE":
                    {
                        DiscordRole role = payload.Deserialize <RoleUpdate>().Role.SetClient(this);

                        if (Config.Cache)
                        {
                            var roles = GuildCache[role.GuildId]._roles;
                            roles[roles.FindIndex(r => r.Id == role.Id)] = role;
                        }

                        Task.Run(() => OnRoleUpdated?.Invoke(this, new RoleEventArgs(role)));
                    }
                    break;

                    case "GUILD_ROLE_DELETE":
                    {
                        DeletedRole role = payload.Deserialize <DeletedRole>().SetClient(this);

                        if (Config.Cache)
                        {
                            GuildCache[role.Guild]._roles.RemoveAll(r => r.Id == role.Id);
                        }

                        Task.Run(() => OnRoleDeleted?.Invoke(this, new RoleDeletedEventArgs(role)));
                    }
                    break;

                    case "GUILD_EMOJIS_UPDATE":
                        var emojis = payload.Deserialize <EmojiContainer>().SetClient(this);

                        if (Config.Cache)
                        {
                            GuildCache[emojis.GuildId]._emojis = emojis.Emojis.ToList();
                        }

                        Task.Run(() => OnEmojisUpdated?.Invoke(this, new EmojisUpdatedEventArgs(emojis)));
                        break;

                    case "CHANNEL_CREATE":
                    {
                        var channel = payload.DeserializeEx <DiscordChannel>().SetClient(this);

                        if (Config.Cache)
                        {
                            if (channel.Type == ChannelType.DM || channel.Type == ChannelType.Group)
                            {
                                PrivateChannels.Add(channel.ToDMChannel());
                            }
                            else
                            {
                                GuildChannel guildChannel = channel.ToGuildChannel();

                                GuildCache[guildChannel.GuildId]._channels.Add(guildChannel);
                            }
                        }

                        Task.Run(() => OnChannelCreated?.Invoke(this, new ChannelEventArgs(channel)));
                    }
                    break;

                    case "CHANNEL_UPDATE":
                    {
                        var channel = payload.DeserializeEx <DiscordChannel>().SetClient(this);

                        if (Config.Cache)
                        {
                            if (channel.Type == ChannelType.DM || channel.Type == ChannelType.Group)
                            {
                                PrivateChannels[PrivateChannels.FindIndex(c => c.Id == channel.Id)] = channel.ToDMChannel();
                            }
                            else
                            {
                                GuildChannel guildChannel = channel.ToGuildChannel();

                                var channels = GuildCache[guildChannel.GuildId]._channels;

                                channels[channels.FindIndex(c => c.Id == guildChannel.Id)] = guildChannel;
                            }
                        }

                        Task.Run(() => OnChannelUpdated?.Invoke(this, new ChannelEventArgs(channel)));
                    }
                    break;

                    case "CHANNEL_DELETE":
                    {
                        var channel = payload.DeserializeEx <DiscordChannel>().SetClient(this);

                        if (Config.Cache)
                        {
                            if (channel.Type == ChannelType.DM || channel.Type == ChannelType.Group)
                            {
                                PrivateChannels.RemoveAll(c => c.Id == channel.Id);
                            }
                            else
                            {
                                GuildCache[channel.ToGuildChannel().GuildId]._channels.RemoveAll(c => c.Id == channel.Id);
                            }
                        }

                        Task.Run(() => OnChannelDeleted?.Invoke(this, new ChannelEventArgs(channel)));
                    }
                    break;

                    case "TYPING_START":
                        Task.Run(() => OnUserTyping?.Invoke(this, new UserTypingEventArgs(payload.Deserialize <UserTyping>())));
                        break;

                    case "MESSAGE_CREATE":
                        var message = payload.Deserialize <DiscordMessage>().SetClient(this);

                        if (Config.Cache)
                        {
                            try
                            {
                                var channel = PrivateChannels.First(c => c.Id == message.Channel.Id);

                                channel.LastMessageId = message.Id;
                            }
                            catch { }
                        }

                        Task.Run(() => OnMessageReceived?.Invoke(this, new MessageEventArgs(message)));
                        break;

                    case "MESSAGE_UPDATE":
                        Task.Run(() => OnMessageEdited?.Invoke(this, new MessageEventArgs(payload.Deserialize <DiscordMessage>().SetClient(this))));
                        break;

                    case "MESSAGE_DELETE":
                        Task.Run(() => OnMessageDeleted?.Invoke(this, new MessageDeletedEventArgs(payload.Deserialize <DeletedMessage>())));
                        break;

                    case "MESSAGE_REACTION_ADD":
                        Task.Run(() => OnMessageReactionAdded?.Invoke(this, new ReactionEventArgs(payload.Deserialize <MessageReactionUpdate>().SetClient(this))));
                        break;

                    case "MESSAGE_REACTION_REMOVE":
                        Task.Run(() => OnMessageReactionRemoved?.Invoke(this, new ReactionEventArgs(payload.Deserialize <MessageReactionUpdate>().SetClient(this))));
                        break;

                    case "GUILD_BAN_ADD":
                        Task.Run(() => OnUserBanned?.Invoke(this, new BanUpdateEventArgs(payload.Deserialize <BanContainer>().SetClient(this))));
                        break;

                    case "GUILD_BAN_REMOVE":
                        Task.Run(() => OnUserUnbanned?.Invoke(this, new BanUpdateEventArgs(payload.Deserialize <BanContainer>().SetClient(this))));
                        break;

                    case "INVITE_CREATE":
                        Task.Run(() => OnInviteCreated?.Invoke(this, payload.Deserialize <InviteCreatedEventArgs>()));
                        break;

                    case "INVITE_DELETE":
                        Task.Run(() => OnInviteDeleted?.Invoke(this, payload.Deserialize <InviteDeletedEventArgs>()));
                        break;

                    case "RELATIONSHIP_ADD":
                        Task.Run(() => OnRelationshipAdded?.Invoke(this, new RelationshipEventArgs(payload.Deserialize <Relationship>().SetClient(this))));
                        break;

                    case "RELATIONSHIP_REMOVE":
                        Task.Run(() => OnRelationshipRemoved?.Invoke(this, new RelationshipEventArgs(payload.Deserialize <Relationship>().SetClient(this))));
                        break;

                    case "CHANNEL_RECIPIENT_ADD":
                    {
                        var recipUpdate = payload.Deserialize <ChannelRecipientUpdate>().SetClient(this);

                        if (Config.Cache)
                        {
                            foreach (var channel in PrivateChannels)
                            {
                                if (channel.Id == recipUpdate.Channel.Id)
                                {
                                    if (channel._recipients == null)
                                    {
                                        channel._recipients = new List <DiscordUser>();
                                    }

                                    channel._recipients.Add(recipUpdate.User);

                                    channel.UpdateSelfJson();

                                    break;
                                }
                            }
                        }
                    }
                    break;

                    case "CHANNEL_RECIPIENT_REMOVE":
                    {
                        var recipUpdate = payload.Deserialize <ChannelRecipientUpdate>().SetClient(this);

                        if (Config.Cache)
                        {
                            foreach (var channel in PrivateChannels)
                            {
                                if (channel.Id == recipUpdate.Channel.Id)
                                {
                                    if (channel._recipients != null)
                                    {
                                        channel._recipients.RemoveAll(u => u.Id == recipUpdate.User.Id);

                                        channel.UpdateSelfJson();
                                    }

                                    break;
                                }
                            }
                        }
                    }
                    break;

                    case "MESSAGE_ACK":         // triggered whenever another person logged into the account acknowledges a message
                        break;

                    case "SESSIONS_REPLACE":
                        Task.Run(() => OnSessionsUpdated?.Invoke(this, new DiscordSessionsEventArgs(payload.Deserialize <List <DiscordSession> >())));
                        break;

                    case "CALL_CREATE":
                    {
                        JObject obj = payload.Deserialize <JObject>();

                        var call        = obj.ToObject <DiscordCall>().SetClient(this);
                        var voiceStates = obj.Value <IReadOnlyList <DiscordVoiceState> >("voice_states").SetClientsInList(this);

                        PrivateVoiceStates[call.Channel.Id] = voiceStates.ToList();

                        Task.Run(() => OnRinging?.Invoke(this, new RingingEventArgs(call, voiceStates)));
                    }
                    break;

                    case "CALL_UPDATE":
                        Task.Run(() => OnCallUpdated?.Invoke(this, new CallUpdateEventArgs(payload.Deserialize <DiscordCall>().SetClient(this))));
                        break;

                    case "CALL_DELETE":
                        ulong channelId = payload.Deserialize <JObject>().Value <ulong>("channel_id");

                        PrivateVoiceStates.Remove(channelId);

                        Task.Run(() => OnCallEnded?.Invoke(this, channelId));
                        break;

                    case "USER_PREMIUM_GUILD_SUBSCRIPTION_SLOT_UPDATE":
                        Task.Run(() => OnBoostUpdated?.Invoke(this, new NitroBoostUpdatedEventArgs(payload.Deserialize <DiscordNitroBoost>().SetClient(this))));
                        break;
                    }
                    break;

                case GatewayOpcode.InvalidSession:
                    LoggedIn = false;

                    this.LoginToGateway();
                    break;

                case GatewayOpcode.Connected:
                    this.LoginToGateway();

                    Task.Run(() =>
                    {
                        int interval = payload.Deserialize <JObject>().GetValue("heartbeat_interval").ToObject <int>();

                        try
                        {
                            while (true)
                            {
                                this.Send(GatewayOpcode.Heartbeat, this.Sequence);
                                Thread.Sleep(interval);
                            }
                        }
                        catch { }
                    });

                    break;
                }
            }
            catch
            {
            }
        }
Beispiel #45
0
 void socket_OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
 {
     this.ShowMsg(this.txtClient, "OnMessage:" + e.Data);
 }
Beispiel #46
0
 private void OnMessageCallBack(object sender, WebSocketSharp.MessageEventArgs arg)
 {
     m_Messages.Enqueue(arg.RawData);
 }
Beispiel #47
0
 private void Receive(object sender, WebSocketSharp.MessageEventArgs e)
 {
     OnReceive?.Invoke(sender, new MessageEventArgs(e.RawData));
 }
Beispiel #48
0
        protected void OnDataRecived(WebSocketSharp.MessageEventArgs e, string id)
        {
            string datasocketId = ToDataSocketID(id);

            TotalMessageRecivedEvents++;
            MemoryStream ms = new MemoryStream(e.RawData);

            WebsocketPipeMessageInfo[] msgs;

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            try
            {
                msgs = DataSocket.ReadMessages(ms).ToArray();
            }
            catch (Exception ex)
            {
                string msg = "Error while reading messages from data socket: " + ex.Message;
                WriteLogMessage(id, msg);
                throw new Exception(msg, ex);
            }

            watch.Stop();
            WriteLogTimeMessage(id, "Read from datasocket", watch.Elapsed.TotalMilliseconds);

            ms.Close();
            ms.Dispose();
            ms = null;

            watch.Reset();
            watch.Start();
            int bytecount = 0;

            MessageEventArgs[] mes = msgs.Select(msg =>
            {
                bytecount = bytecount + msg.Data.Length;
                TMessage o;
                try
                {
                    o = Serializer.FromBytes(msg.Data);;
                }
                catch (Exception ex)
                {
                    var str = "Error desrializing message. " + ex.Message;
                    WriteLogMessage(id, str);
                    throw new Exception(str, ex);
                }

                return(new MessageEventArgs(o, msg.NeedsResponse, id));
            }).ToArray();

            WriteLogTimeMessage(id, "Deserialzed " + msgs.Length + " messages with " + bytecount + " [bytes] ", watch.Elapsed.TotalMilliseconds);

            watch.Stop();
            watch.Reset();
            watch.Start();
            foreach (var me in mes)
            {
                if (TriggerWaitHandle(datasocketId, me.Message)) // this message is a response.
                {
                    continue;
                }

                OnMessage(me);
            }
            watch.Stop();
            WriteLogTimeMessage(id, "Handled evnets for " + msgs.Length + " messages", watch.Elapsed.TotalMilliseconds);
        }
 private static void Ws_OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
 {
     Console.WriteLine("Data: " + e.Data);
     Console.WriteLine("RawData: " + e.RawData);
 }
Beispiel #50
0
 protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
 {
     Pipe.OnDataRecived(e, this.ID);
     base.OnMessage(e);
 }
Beispiel #51
0
 private void OnMessage_1(object sender, WebSocketSharp.MessageEventArgs e)
 {
     OnMessage(e.RawData);
 }
Beispiel #52
0
        private void SocketDataReceived(object sender, WebSocketSharp.MessageEventArgs result)
        {
            GatewayResponse payload = result.Data.Deserialize <GatewayResponse>();

            Sequence = payload.Sequence;

            switch (payload.Opcode)
            {
            case GatewayOpcode.Event:
                switch (payload.Title)
                {
                case "READY":
                    LoggedIn = true;
                    Login login = payload.Deserialize <Login>().SetClient(this);
                    this.User      = login.User;
                    this.SessionId = login.SessionId;
                    OnLoggedIn?.Invoke(this, new LoginEventArgs(login));
                    break;

                case "USER_SETTINGS_UPDATE":
                    OnSettingsUpdated?.Invoke(this, new SettingsUpdatedEventArgs(payload.Deserialize <Settings>()));
                    break;

                case "USER_UPDATE":
                    User user = payload.Deserialize <User>().SetClient(this);

                    if (user.Id == User.Id)
                    {
                        User.Update(user);
                    }

                    OnUserUpdated?.Invoke(this, new UserEventArgs(user));
                    break;

                case "GUILD_CREATE":
                    OnJoinedGuild?.Invoke(this, new GuildEventArgs(payload.Deserialize <Guild>().SetClient(this)));
                    break;

                case "GUILD_UPDATE":
                    OnGuildUpdated?.Invoke(this, new GuildEventArgs(payload.Deserialize <Guild>().SetClient(this)));
                    break;

                case "GUILD_DELETE":
                    OnLeftGuild?.Invoke(this, new GuildEventArgs(payload.Deserialize <Guild>().SetClient(this)));
                    break;

                case "GUILD_MEMBER_ADD":
                    OnUserJoinedGuild?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMemberUpdate>().SetClient(this).Member));
                    break;

                case "GUILD_MEMBER_REMOVE":
                    OnUserLeftGuild?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMemberUpdate>().SetClient(this).Member));
                    break;

                case "GUILD_MEMBER_UPDATE":
                    OnGuildMemberUpdated?.Invoke(this, new GuildMemberEventArgs(payload.Deserialize <GuildMember>().SetClient(this)));
                    break;

                case "GUILD_MEMBERS_CHUNK":
                    OnGuildMembersReceived?.Invoke(this, new GuildMembersEventArgs(payload.Deserialize <GuildMemberList>().Members.SetClientsInList(this)));
                    break;

                case "PRESENCE_UPDATE":
                    OnUserPresenceUpdated?.Invoke(this, new PresenceUpdatedEventArgs(payload.Deserialize <PresenceUpdate>()));
                    break;

                case "VOICE_STATE_UPDATE":
                    VoiceState state = payload.Deserialize <VoiceState>().SetClient(this);

                    if (state.ChannelId != null)
                    {
                        OnUserJoinedVoiceChannel?.Invoke(this, new VoiceStateEventArgs(state));
                    }
                    else
                    {
                        OnUserLeftVoiceChannel?.Invoke(this, new VoiceStateEventArgs(state));
                    }
                    break;

                case "GUILD_ROLE_CREATE":
                    OnRoleCreated?.Invoke(this, new RoleEventArgs(payload.Deserialize <RoleContainer>().Role.SetClient(this)));
                    break;

                case "GUILD_ROLE_UPDATE":
                    OnRoleUpdated?.Invoke(this, new RoleEventArgs(payload.Deserialize <RoleContainer>().Role.SetClient(this)));
                    break;

                case "GUILD_EMOJIS_UPDATE":
                    OnEmojisUpdated?.Invoke(this, new EmojisUpdatedEventArgs(payload.Deserialize <EmojiContainer>().SetClient(this)));
                    break;

                case "CHANNEL_CREATE":
                    OnChannelCreated?.Invoke(this, new ChannelEventArgs(payload.Deserialize <GuildChannel>().SetClient(this)));
                    break;

                case "CHANNEL_UPDATE":
                    OnChannelUpdated?.Invoke(this, new ChannelEventArgs(payload.Deserialize <GuildChannel>().SetClient(this)));
                    break;

                case "CHANNEL_DELETE":
                    OnChannelDeleted?.Invoke(this, new ChannelEventArgs(payload.Deserialize <GuildChannel>().SetClient(this)));
                    break;

                case "TYPING_START":
                    OnUserTyping?.Invoke(this, new UserTypingEventArgs(payload.Deserialize <UserTyping>()));
                    break;

                case "MESSAGE_CREATE":
                    OnMessageReceived?.Invoke(this, new MessageEventArgs(payload.Deserialize <Message>().SetClient(this)));
                    break;

                case "MESSAGE_UPDATE":
                    OnMessageEdited?.Invoke(this, new MessageEventArgs(payload.Deserialize <Message>().SetClient(this)));
                    break;

                case "MESSAGE_DELETE":
                    OnMessageDeleted?.Invoke(this, new MessageDeletedEventArgs(payload.Deserialize <DeletedMessage>()));
                    break;

                case "MESSAGE_REACTION_ADD":
                    OnMessageReactionAdded?.Invoke(this, new ReactionEventArgs(payload.Deserialize <MessageReactionUpdate>().SetClient(this)));
                    break;

                case "MESSAGE_REACTION_REMOVE":
                    OnMessageReactionRemoved?.Invoke(this, new ReactionEventArgs(payload.Deserialize <MessageReactionUpdate>().SetClient(this)));
                    break;

                case "GUILD_BAN_ADD":
                    OnUserBanned?.Invoke(this, new BanUpdateEventArgs(payload.Deserialize <BanContainer>().SetClient(this)));
                    break;

                case "GUILD_BAN_REMOVE":
                    OnUserUnbanned?.Invoke(this, new BanUpdateEventArgs(payload.Deserialize <BanContainer>().SetClient(this)));
                    break;

                case "RELATIONSHIP_ADD":
                    OnRelationshipAdded?.Invoke(this, new RelationshipEventArgs(payload.Deserialize <Relationship>().SetClient(this)));
                    break;

                case "RELATIONSHIP_REMOVE":
                    OnRelationshipRemoved?.Invoke(this, new RelationshipEventArgs(payload.Deserialize <Relationship>().SetClient(this)));
                    break;

                case "USER_CONNECTIONS_UPDATE":
                    Task.Run(() =>
                    {
                        DiscordProfile profile = this.User.GetProfile();
                        OnProfileUpdated?.Invoke(this, new ProfileUpdatedEventArgs(profile));
                    });
                    break;
                }
                break;

            case GatewayOpcode.InvalidSession:
                this.LoginToGateway();
                break;

            case GatewayOpcode.Connected:
                if (!LoggedIn)
                {
                    this.LoginToGateway();
                }
                else
                {
                    this.Resume();
                }

                this.StartHeartbeatHandlersAsync(payload.Deserialize <JObject>().GetValue("heartbeat_interval").ToObject <uint>());
                break;
            }
        }
Beispiel #53
0
    private void message(object sender, WebSocketSharp.MessageEventArgs e)
    {
        var msg = Api.Proto.ParseMessage(e.RawData);

        _reader.Queue = msg;
    }
Beispiel #54
0
        private void OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
        {
            packArgs pack = parser.paser(e.Data);

            packparse_over(pack);
        }
Beispiel #55
0
        protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
        {
            // Basically just echo whatever's sent here

            Console.WriteLine(" - a client says " + e.Data);

            JObject json          = JObject.Parse(e.Data);
            string  serverRequest = (string)json["ServerRequest"];

            if (string.IsNullOrEmpty(serverRequest))
            {
                // Not a server request, so just echo the contents to everybody
                Sessions.Broadcast(e.Data);
            }

            switch (serverRequest)
            {
            case "AddBitcoinAddress":
                FrontendLoop.AddBitcoinAddress((string)json["Address"]);
                break;

            case "Metapackage":
                ProcessMetapackage((string)json["XmlData"]);
                break;

            case "Ping":
                // TODO: Request heartbeat from backend
                // Sessions.Broadcast("{\"messageType\":\"Heartbeat\"}");
                break;

            case "ConvertPdf":
                try
                {
                    JArray pdfFilesArray       = (JArray)json["PdfFiles"];
                    JArray pdfClientNamesArray = (JArray)json["ClientFileNames"];

                    List <RasterizationTarget> rasterizationTargets = new List <RasterizationTarget>();
                    for (int loop = 0; loop < pdfFilesArray.Count; loop++)
                    {
                        rasterizationTargets.Add(new RasterizationTarget
                        {
                            FullyQualifiedFileName = Document.StorageRoot + (string)pdfFilesArray[loop],
                            ClientFileName         = (string)pdfClientNamesArray[loop]
                        });
                    }

                    PdfProcessor pdfMaker = new PdfProcessor();
                    pdfMaker.RasterizationProgress += BroadcastGuidProgress;
                    pdfMaker.RasterizeMany(rasterizationTargets.ToArray(), (string)json["Guid"], _authority.Person,
                                           _authority.Organization);
                }
                catch (Exception exc)
                {
                    Sessions.Broadcast("{\"messageType\":\"Debug\",\"data\":\"Exception - " + exc.GetType() + " - " + exc.ToString().Replace("\"", "\\\"") + "\"}");
                }

                break;

            case "ConvertPdfHires":
                // Send to backend
                JObject backendRequest = new JObject();
                backendRequest["BackendRequest"] = "ConvertPdfHires";
                backendRequest["DocumentId"]     = json["DocumentId"];
                FrontendLoop.SendMessageUpstream(backendRequest);
                break;

            default:
                // do nothing;
                break;
            }
        }
        public IEnumerator PostJsonData(string url, string data, Action callback = null)
        {
            while (!isNeedAsync && false == IsSyncHttpDone)
            {
                yield return(0);
            }

            IsSyncHttpDone        = false;
            _lastMessageEventArgs = null;
            header = new WWWForm();
            Dictionary <string, string> headers = header.headers;

            byte[] rawData = Encoding.UTF8.GetBytes(data);
            headers["Content-Type"] = "application/json";
            headers["Accept"]       = "application/json";

            DateTime date = DateTime.Now;
            string   time = date.ToString("ddd, yyyy-mm-dd HH':'mm':'ss 'UTC'", DateTimeFormatInfo.InvariantInfo);

            headers["Date"] = time;

            //www = new WWW(WWW.EscapeURL(url), rawData, headers);
            WWW www = new WWW(url, rawData, headers);

            yield return(www);

            //throw out events
            if (www.error != null)
            {
                Debug.Log("error is [PostJsonData]:" + www.error + "  [Data]:" + rawData);
                error(www.error);
            }
            else
            {
                //最多等5s...
                int maxTimeout = MaxTimes;
                while (!www.isDone)
                {
                    yield return(new WaitForSeconds(WaitPerTime));

                    maxTimeout--;
                    if (maxTimeout <= 0)
                    {
                        IsSyncHttpDone = true;
                        yield break;
                    }
                }

                Debug.Log("request ok response: " + www.text);

                _lastMessageEventArgs = new WebSocketSharp.MessageEventArgs(WebSocketSharp.Opcode.Text, www.text);
                IsSyncHttpDone        = true;

                if (callback != null)
                {
                    callback.Invoke();
                }

                if (isNeedAsync)
                {
                    enqueueToMessageEventQueue(_lastMessageEventArgs);
                }

                /*
                 * JsonData jd = JsonMapper.ToObject(www.text);
                 *
                 * string memberId = jd["memberId"].ToString();
                 * string bonusPoint = jd["bonusPoint"].ToString();
                 * string nickName = jd["nickName"].ToString();*/
            }
        }
Beispiel #57
0
 protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
 {
     base.OnMessage(e);
 }
 public void ParseReponse(object sender, WebSocketSharp.MessageEventArgs message)
 {
     websocketClient.OnMessage -= ParseReponse;
     Debug.LogFormat("MESSAGE {0}\n\nSent:\n{1}\nExpected:\n{2}\nGot:\n{3}\n", message.Data == expectedResponse ? "MATCHES" : "MISMATCHES!", this.sentMessage, expectedResponse, message.Data);
     callback(message.Data == expectedResponse);
 }