상속: IMessageWebSocketMessageReceivedEventArgs
        void FayeMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
            
            string message;
            using (var reader = args.GetDataReader()) {
                message = reader.ReadString(reader.UnconsumedBufferLength);
            }
            message = message.Trim().TrimStart('[').TrimEnd(']');

            var obj = Helpers.Deserialize<FayeResponse>(message);

            if (obj.Channel == "/meta/handshake" && !_asyncHandshake) {
                FinishHandshake(message);
                Send(new ConnectRequest());
                return;
            }

            if (obj.Channel == "/meta/connect") {
                Send(new ConnectRequest());
            }

            if (obj.Successful != null && obj.Id != null) {
                Guid guid;
                if (Guid.TryParse(obj.Id, out guid)) {
                    if (_requestWaiters.ContainsKey(guid)) {
                        _requestSuccesses[guid] = (bool)obj.Successful;
                        _requestResponses[guid] = message;
                        Debug.WriteLine("Doing set for response on " + obj.Channel);
                        _requestWaiters[guid].Set();
                        return;
                    }
                }
            }
            Event(MessageReceived, new FayeMessageEventArgs { Data = message, Channel = obj.Channel });
        }
        void _socket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {

            if (this.Message != null)
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        //Get the DataReader
                        using (var dataReader = new JsonTextReader(new StreamReader(ms)))
                        {
                            args.GetDataStream().AsStreamForRead().CopyTo(ms);
                            ms.Position = 0;
                            dataReader.SupportMultipleContent = true;
                            while (dataReader.Read())
                            {
                                var parsedMessage = JArray.Load(dataReader);
                                Message(this, new WampMessageEventArgs(parsedMessage));
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    var status = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.HResult);
                    if (status != Windows.Web.WebErrorStatus.Unknown)
                        this.OnError(this, status);
                }
            }
        }
예제 #3
0
		private void socket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
		{
			using (StreamReader streamReader = new StreamReader(args.GetDataStream().AsStreamForRead()))
			{
				using (JsonReader jsonReader = new JsonTextReader(streamReader))
				{
					JObject jmessage = JObject.Load(jsonReader);


				}
			}
		}
예제 #4
0
 //Sends the data
 private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (DataReader reader = args.GetDataReader())
         {
             reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
             string read = reader.ReadString(reader.UnconsumedBufferLength);
         }
     }
     catch (Exception ex)
     {
         String.Format("There is an error sending the data"); 
     }
 }
        private async void Sck_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {

            //[email protected]("Message received " + args);

            if (args.MessageType == SocketMessageType.Utf8)
            {
                Windows.Storage.Streams.DataReader messageReader = args.GetDataReader();
                messageReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
                com.codename1.io.websocket.WebSocket.messageReceived(id, messageString);
            } else
            {

                Windows.Storage.Streams.IInputStream readStream = args.GetDataStream();
                byte[] readBuffer = new byte[4096];
                try
                {
                    while (true)
                    {
                        if (sender != sck)
                        {
                            return;
                        }

                        IBuffer res = await readStream.ReadAsync(readBuffer.AsBuffer(), (uint)readBuffer.Length, 0);
                        if (res.Length == 0)
                        {
                            return;
                        }
                        byte[] resArr = new byte[res.Length];
                        res.CopyTo(resArr);
                        com.codename1.io.websocket.WebSocket.messageReceived(1, resArr);

                    }
                } catch (Exception ex)
                {
                    com.codename1.io.websocket.WebSocket.errorReceived(id, ex.Message, ex.HResult);
                }
                
            }
        }
예제 #6
0
        private void Mws_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            // TODO
            // 1. get the message out of the args.
            // 2. add it to the outputBox content. 
            // Note that you're not necessarily on the UI thread when called asynchronously, 
            // and marshall over to the UI thread rather than just stuffing the UI element.
            using (DataReader reader = args.GetDataReader())
            {
                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                string read = reader.ReadString(reader.UnconsumedBufferLength);
                MarshalText(outputBox, read + "\r\n");
            }

        }
        private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
        {
            using (DataReader dataReader = args.GetDataReader())
            {
                byte[] bytes = new byte[dataReader.UnconsumedBufferLength];
                dataReader.ReadBytes(bytes);

                Gabriel.ToClient toClient = Gabriel.ToClient.Parser.ParseFrom(bytes);

                if (toClient.ResultWrapper == null)
                {
                    // Set num tokens on welcome message
                    lock (_tokenLock)
                    {
                        _numTokens = toClient.NumTokens;
                    }
                    return;
                }

                // We only return one to avoid race conditions when we have multiple messages in flight
                lock (_tokenLock)
                {
                    _numTokens++;
                }

                Gabriel.ResultWrapper resultWrapper = toClient.ResultWrapper;
                if (resultWrapper.Status != Gabriel.ResultWrapper.Types.Status.Success)
                {
                    UnityEngine.Debug.Log("Output status was: " + resultWrapper.Status);
                    return;
                }

                Instruction.EngineFields newEngineFields = resultWrapper.EngineFields.Unpack <Instruction.EngineFields>();
                if (newEngineFields.UpdateCount <= _engineFields.UpdateCount)
                {
                    // There was no update or there was an update based on a stale frame
                    return;
                }

                for (int i = 0; i < resultWrapper.Results.Count(); i++)
                {
                    Gabriel.ResultWrapper.Types.Result result = resultWrapper.Results[i];

                    if (!result.EngineName.Equals(Const.ENGINE_NAME))
                    {
                        UnityEngine.Debug.LogError("Got result from engine " + result.EngineName);
                    }

                    if (result.PayloadType == Gabriel.PayloadType.Text)
                    {
                        _speechFeedback = result.Payload.ToStringUtf8();
                        textToSpeechManager.SpeakText(_speechFeedback);
                    }
                }

                _engineFields = newEngineFields;
                UpdateHologram(newEngineFields, resultWrapper.FrameId);
            }
        }
예제 #8
0
        /// <summary>
        ///  Raw websocket messages from server - convert to message types and call subscribers of events and/or callbacks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void mws_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            string read = null;
            try
            {
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    read = reader.ReadString(reader.UnconsumedBufferLength);
                    Debug.WriteLine("[SOCKET_IO]: < " + read);
                }
                IMessage iMsg = SocketIOClient.Messages.Message.Factory(read);

                if (iMsg.Event == "responseMsg")
                    Debug.WriteLine(string.Format("InvokeOnEvent: {0}", iMsg.RawMessage));

                switch (iMsg.MessageType)
                {
                    case SocketIOMessageTypes.Disconnect:
                        this.OnMessageEvent(iMsg);
                        if (string.IsNullOrWhiteSpace(iMsg.Endpoint)) // Disconnect the whole socket
                            this.Close();
                        break;
                    case SocketIOMessageTypes.Heartbeat:
                        this.OnHeartBeatTimerCallback(null);
                        break;
                    case SocketIOMessageTypes.Connect:
                    case SocketIOMessageTypes.Message:
                    case SocketIOMessageTypes.JSONMessage:
                    case SocketIOMessageTypes.Event:
                    case SocketIOMessageTypes.Error:
                        this.OnMessageEvent(iMsg);
                        break;
                    case SocketIOMessageTypes.ACK:
                        this.registrationManager.InvokeCallBack(iMsg.AckId, iMsg.Json);
                        break;
                    default:
                        Debug.WriteLine("unknown mws message Received...");
                        break;
                }
            }
            catch (Exception ex) // For debugging
            {
                this.mwsState = WebSocketState.Closed;
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                Debug.WriteLine("mws_MessageReceived::exception : " + status);
                this.OnErrorEvent(this, new ErrorEventArgs(status.ToString(), ex));
                //this.Close();
            }
        }
 private void OnMessageReceived(int id, MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (var reader = args.GetDataReader())
         {
             var message = reader.ReadString(reader.UnconsumedBufferLength);
             SendEvent("websocketMessage", new JObject
             {
                 { "id", id },
                 { "data", message },
             });
         }
     }
     catch (Exception ex)
     {
         OnError(id, ex);
     }
 }
 public MessageReceivedEventArgsWrapper(MessageWebSocketMessageReceivedEventArgs messageReceivedEventArgs)
 {
     _messageReceivedEventArgs = messageReceivedEventArgs;
 }
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                MarshalText(OutputField, "Message Received; Type: " + args.MessageType + "\r\n");
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    MarshalText(OutputField, read + "\r\n");
                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                MarshalText(OutputField, "Error: " + status + "\r\n");

                MarshalText(OutputField, ex.Message + "\r\n");
            }
        }
예제 #12
0
 private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (DataReader reader = args.GetDataReader())
         {
             reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
             string read = reader.ReadString(reader.UnconsumedBufferLength);
         }
     }
     catch (Exception ex)
     {
         WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
     }
 }
예제 #13
0
        private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            using (DataReader reader = args.GetDataReader())
            {
                uint dataAvailable;
                while ((dataAvailable = reader.UnconsumedBufferLength) > 0)
                {
                    ArraySegment<byte> buffer;
                    try
                    {
                        buffer = _receiveAsyncBufferTcs.Task.GetAwaiter().GetResult();
                    }
                    catch (OperationCanceledException) // Caused by Abort call on WebSocket
                    {
                        return;
                    }
                    
                    _receiveAsyncBufferTcs = new TaskCompletionSource<ArraySegment<byte>>();
                    WebSocketMessageType messageType;
                    if (args.MessageType == SocketMessageType.Binary)
                    {
                        messageType = WebSocketMessageType.Binary;
                    }
                    else
                    {
                        messageType = WebSocketMessageType.Text;
                    }

                    bool endOfMessage = false;
                    uint readCount = Math.Min(dataAvailable, (uint) buffer.Count);
                    var dataBuffer = reader.ReadBuffer(readCount);
                    // Safe to cast readCount to int as the maximum value that readCount can be is buffer.Count.
                    dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int) readCount);
                    if (dataAvailable == readCount)
                    {
                        endOfMessage = true;
                    }

                    WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int) readCount, messageType,
                        endOfMessage);
                    _webSocketReceiveResultTcs.TrySetResult(recvResult);
                }
            }
        }
예제 #14
0
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            // Dispatch the event to the UI thread so we can update UI.
            var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                AppendOutputLine("Message Received; Type: " + args.MessageType);
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                    try
                    {
                        string read = reader.ReadString(reader.UnconsumedBufferLength);
                        AppendOutputLine(read);
                    }
                    catch (Exception ex)
                    {
                        AppendOutputLine(MainPage.BuildWebSocketError(ex));
                        AppendOutputLine(ex.Message);
                    }
                }
            });
        }
예제 #15
0
 /// <summary>
 /// The message web socket on message received.
 /// </summary>
 /// <param name="sender">
 /// The sender.
 /// </param>
 /// <param name="args">
 /// The args.
 /// </param>
 private void MessageWebSocketOnMessageReceived(
     MessageWebSocket sender, 
     MessageWebSocketMessageReceivedEventArgs args)
 {
     using (var reader = args.GetDataReader())
     {
         reader.UnicodeEncoding = UnicodeEncoding.Utf8;
         var stringRead = reader.ReadString(reader.UnconsumedBufferLength);
         this.receiveQueue.Add(stringRead);
     }
 }
예제 #16
0
        private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            var t = args;
            HasRecieved = false;

            _deferral.Complete();
        }
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            ChatMessage msg = null;
            try
            {
                using (DataReader reader = args.GetDataReader())
                {
                    // get message and deserialize to ChatMessage
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    msg = JsonConvert.DeserializeObject<ChatMessage>(read);
                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                // Add your specific error-handling code here.
            }

            // Add item to the local queue
            _queue.Enqueue(msg);

            // Dispatch the queue handler
            this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, DisplayMessage);
        }
 private void Message_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
 }
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    string read = reader.ReadString(reader.UnconsumedBufferLength);

                    // parse the message 
                    JObject messageObject = null;
                    try
                    {
                        messageObject = JObject.Parse(read);
                    }
                    catch(Exception e)
                    {
                        messageObject = null;
                        App.AddNotification(new Notification() { Title = "Error Parsing WebSocket Data Package", Message = e.Message });
                    }

                    // if we have an object and it is of type play
                    if (messageObject != null && "Play" == (string)messageObject["MessageType"])
                    {
                        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            Frame rootFrame = Window.Current.Content as Frame;

                            rootFrame.Navigate(typeof(PlayerPage), messageObject);
                        });
                    }


                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
                // Add your specific error-handling code here.
            }
        }
 void _websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
 {
     try
     {
         using (var reader = args.GetDataReader())
         {
             reader.UnicodeEncoding = UnicodeEncoding.Utf8;
             var text = reader.ReadString(reader.UnconsumedBufferLength);
             OnMessage(text);
         }
     }
     catch
     {
         OnError("Failed to read message.");
     }
 }
        private string GetOnMessage(MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                var dataStream = args.GetDataStream();
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    return read;
                }
            }
            catch (Exception ex)
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
            }
            return String.Empty;
        }
        private void webSocketClient_MessageReceivedV2(object sender, MessageWebSocketMessageReceivedEventArgs e)
        {
            try
            {
                var dataStream = e.GetDataStream();
                using (DataReader reader = e.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    IDictionary<string, object> e1 = AVClient.DeserializeJsonString(read);
                    if (this.m_onRecevied == null)
                        return;
                    this.m_onRecevied((object)this, e1);
                }
               
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
        }
        private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            using (var reader = args.GetDataReader())
            {
                reader.UnicodeEncoding = UnicodeEncoding.Utf8;
                var response = reader.ReadString(reader.UnconsumedBufferLength);

                var json = JObject.Parse(response);
                if (json.ContainsKey("replyID"))
                {
                    var replyId = json.Value<int>("replyID");
                    var callback = default(TaskCompletionSource<JToken>);
                    if (_callbacks.TryGetValue(replyId, out callback))
                    {
                        var result = default(JToken);
                        if (json != null && json.TryGetValue("result", out result))
                        {
                            if (result.Type == JTokenType.String)
                            {
                                callback.TrySetResult(JToken.Parse(result.Value<string>()));
                            }
                            else
                            {
                                callback.TrySetResult(result);
                            }
                        }
                        else
                        {
                            callback.TrySetResult(null);
                        }
                    }
                }
            }
        }
 private IDictionary<string, object> CaptureResponseByCMDId(string cmdId, MessageWebSocketMessageReceivedEventArgs e)
 {
     IDictionary<string, object> dictionary = null;
     IDictionary<string, object> data = AVClient.DeserializeJsonString(GetOnMessage(e));
     if (AVRMProtocolUtils.CaptureValueFromDictionary<long>(data, "i").ToString() == cmdId)
         dictionary = data;
     return dictionary;
 }
예제 #25
0
        private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Message Received; Type: " + args.MessageType);
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    string read = reader.ReadString(reader.UnconsumedBufferLength);

                    //Convert to JSON
                    if (read != "")
                    {

                    }
                    System.Diagnostics.Debug.WriteLine(read);
                }
            }
            catch (Exception ex) // For debugging
            {
                WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

                if (status == WebErrorStatus.Unknown)
                {
                    throw;
                }

                // Normally we'd use the status to test for specific conditions we want to handle specially,
                // and only use ex.Message for display purposes.  In this sample, we'll just output the
                // status for debugging here, but still use ex.Message below.
                System.Diagnostics.Debug.WriteLine("Error: " + status);

                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
 private void webSocketClient_MessageReceived(object sender, MessageWebSocketMessageReceivedEventArgs e)
 {
     string[] array = new string[6]
     {
         "session",
         "direct",
         "presence",
         "ackreq",
         "ack",
         "room"
     };
     EventHandler<AVIMEventArgs>[] eventHandlerArray = new EventHandler<AVIMEventArgs>[6]
     {
         this.m_OnSessionChanged,
         this.m_OnMessage,
         this.m_OnPresenceChanged,
         this.m_OnAskReqGet,
         this.m_OnMessageSent,
         this.m_OnGroupAction
     };
     RealtimeMessageHooks.CreateAVSessionEventArgs[] sessionEventArgsArray = new RealtimeMessageHooks.
         CreateAVSessionEventArgs[6]
     {
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAVSession),
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAVMessage),
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAVPresence),
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAckReq),
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAck),
         new RealtimeMessageHooks.CreateAVSessionEventArgs(this.ProcessAVGroupOp)
     };
     IDictionary<string, object> data = AVClient.DeserializeJsonString(GetOnMessage(e));
     try
     {
         string str = AVRMProtocolUtils.CaptureValueFromDictionary<string>(data, "cmd");
         int index = Array.IndexOf<string>(array, str);
         if (index <= -1)
             return;
         EventHandler<AVIMEventArgs> eventHandler = eventHandlerArray[index];
         AVIMEventArgs e1 = sessionEventArgsArray[index](data);
         if (eventHandler == null)
             return;
         eventHandler((object) this, e1);
     }
     catch
     {
     }
 }
예제 #27
0
 private void MessageReceived(MessageWebSocket webSocket, MessageWebSocketMessageReceivedEventArgs eventArgs)
 {
     MessageReceived(new MessageReceivedEventArgsWrapper(eventArgs), _connection);
 }
예제 #28
0
        private void HandleMessage(MessageWebSocketMessageReceivedEventArgs args)
        {
            string message;
            DataReader reader = null;
            try
            {
                try
                {
                    reader = args.GetDataReader();
                }
                catch
                {
                    try
                    {
                        _webSocket.Close(1001, "Abnormal Closure");
                    }
                    catch
                    {
                        HandleConnectionClose();
                    }
                    return;
                }

                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                message = reader.ReadString(reader.UnconsumedBufferLength);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }

            var json = JObject.Parse(message);
            var requestId = (string)json["requestId"];

            if (requestId == null)
            {
                // handle server notifications
                var action = (string)json["action"];
                switch (action)
                {
                    case "notification/insert":
                        {
                            var notification = Deserialize<DeviceNotification>(json);
                            InvokeSubscriptionCallback(notification.SubscriptionId, notification.Notification.Timestamp.Value, notification.Notification);
                        }
                        return;

                    case "command/insert":
                        {
                            var command = Deserialize<DeviceCommand>(json);
                            InvokeSubscriptionCallback(command.SubscriptionId, command.Command.Timestamp.Value, command.Command);
                        }
                        return;

                    case "command/update":
                        {
                            var command = Deserialize<Command>((JObject)json["command"]);
                            InvokeCommandCallback(command);
                        }
                        return;
                }
            }

            // handle responses to client requests
            RequestInfo requestInfo = null;
            lock (_requests)
            {
                if (_requests.TryGetValue(requestId, out requestInfo))
                    _requests.Remove(requestId);
            }
            if (requestInfo != null)
                requestInfo.SetResult(json);
        }
예제 #29
0
        private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                using (var datastr = args.GetDataStream().AsStreamForRead())
                    using (var ms = new MemoryStream())
                    {
                        datastr.CopyTo(ms);
                        ms.Position = 0;
                        byte[] data = new byte[ms.Length];
                        ms.Read(data, 0, (int)ms.Length);
                        int index = 0;
                        int count = data.Length;
                        using (var decompressed = new MemoryStream())
                        {
                            if (data[0] == 0x78)
                            {
                                _compressed.Write(data, index + 2, count - 2);
                                _compressed.SetLength(count - 2);
                            }
                            else
                            {
                                _compressed.Write(data, index, count);
                                _compressed.SetLength(count);
                            }

                            _compressed.Position = 0;
                            if (decompressed == null)
                            {
                                return;
                            }
                            _decompressor.CopyTo(decompressed);
                            _compressed.Position  = 0;
                            decompressed.Position = 0;
                            using (var reader = new StreamReader(decompressed))
                                OnMessageReceived(reader.ReadToEnd());
                        }
                    }
            }
            catch (Exception)
            {
                FinishedTask = true;
                UpdateLastRunStatus("There was a problem while decrypting a websocket message on the last run");
            }
        }
        void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            var ev = _onMessageReceived;

            if (ev == null)
                return;

            try
            {
                using (var reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = UnicodeEncoding.Utf8;
                    var read = reader.ReadString(reader.UnconsumedBufferLength);
                    ev(read);
                }
            }
            catch
            {

            }

        }
예제 #31
0
        private async void WebSocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            StreamReader reader = new StreamReader(args.GetDataStream().AsStreamForRead(), System.Text.Encoding.UTF8);

            // get the result in and check if its of type message
            string result = null;
            result = await reader.ReadToEndAsync();
            WriteToOutputBox(result);
            JObject responseObject = JObject.Parse(result);
            string responseType = (string)responseObject["type"];
            if (responseType == "message")
            {
                // then check if it was from the general channel
                string channel = (string)responseObject["channel"];
                if (channel == generalChannelId)
                {
                    // then try to pull the user
                    string sendingUser = (string)responseObject["user"];
                    if (string.IsNullOrEmpty(sendingUser))
                    {
                        return;
                    }
                    SlackUser user = GetSlackUser(sendingUser);
                    if (user == null)
                    {
                        return;
                    }
                    // and pull what they said
                    string messageText = (string)responseObject["text"];

                    // construct our output message
                    string outputMessage = "";
                    if (user.FirstName != null)
                    {
                        outputMessage += user.FirstName + ": ";
                    }
                    else if (user.RealName != null)
                    {
                        outputMessage += user.RealName + ": ";
                    }
                    else
                    {
                        outputMessage += user.Username + ": ";
                    }

                    SmsUser smsToUser = null;
                    string rest = null;
                    if (messageText.StartsWith("<@"))
                    {
                        // if they are an actual slack member then pull up their info using their id
                        int nextBracket = messageText.IndexOf('>');
                        if (nextBracket == -1)
                        {
                            return;
                        }
                        string userId = messageText.Substring(2, nextBracket - 2);
                        SlackUser slackToUser = GetSlackUser(userId);
                        if (slackToUser == null)
                        {
                            return;
                        }

                        // and then try to find their SMS info
                        smsToUser = GetSmsUserByName(slackToUser.Username);
                        if (smsToUser == null)
                        {
                            smsToUser = GetSmsUserByName(slackToUser.FirstName);
                        }
                        if (smsToUser == null)
                        {
                            return;
                        }
                        rest = messageText.Substring(nextBracket + 1);
                    }
                    foreach (SmsUser smsUser in Secrets.SmsUsers)
                    {
                        if (smsUser.RealName == null)
                        {
                            // SMS user needs to at least have a real name
                            return;
                        }
                        // if they arent a slack member then just match using their name
                        if (messageText.StartsWith("@" + smsUser.RealName.ToLower()))
                        {
                            smsToUser = smsUser;
                            rest = messageText.Substring(smsToUser.RealName.Length + 1);
                            break;
                        }
                    }
                    if (smsToUser == null)
                    {
                        return;
                    }
                    if (rest.StartsWith(":"))
                    {
                        rest = rest.Substring(1);
                    }
                    rest = rest.Trim();
                    outputMessage += rest;

                    // then send the message to them
                    Message sentMessage = null;
                    try
                    {
                        twilioClient = new TwilioRestClient(Secrets.TwilioSid, Secrets.TwilioAuthToken);
                        sentMessage = twilioClient.SendMessage(Secrets.TwilioNumber, smsToUser.PhoneNumber, outputMessage);
                    }
                    catch (Exception ex)
                    {
                        WriteToOutputBox("Twilio SendMessage Exception: " + ex.Message);
                    }
                }
            }
            if (responseType == "team_migration_started")
            {
                // hold my socket we're going in
                // server is going down: https://api.slack.com/events/team_migration_started
                serverIsDead = true;
                // we shoudn't probably call ConnectToWebSocket here because we need this method to exit
                // because ConnectToWebSocket turns everything into null
                // so I stuck it in the listener since that's separate
                return;
            }
        }
예제 #32
0
 private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
 {
     Debug.Log("message received");
     try
     {
         using (DataReader dataReader = args.GetDataReader())
         {
             dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
             string    messageString = dataReader.ReadString(dataReader.UnconsumedBufferLength);
             JsonArray msgcontent    = JsonObject.Parse(messageString).GetNamedArray("message");
             Debug.Log("Message received from MessageWebSocket: " + msgcontent);
             //this.messageWebSocket.Dispose(); //this closes the websocket
             //do something with the message
             try
             {
                 foreach (IJsonValue message in msgcontent)
                 {
                     if (message.ValueType == JsonValueType.Object)
                     {
                         JsonObject messageObject = message.GetObject();
                         if (messageObject.GetNamedString("type") == "sensor") //{message: [{ type: 'sensor', id: 'temp1', data: '23.5'},
                         {                                                     //           { type: 'UIaction', id: 'ventilation', data: 'on'}]}
                             //update sensor with the received data
                             string sensor = messageObject.GetNamedString("id");
                             double data   = messageObject.GetNamedValue("data").GetNumber();
                             UpdateStuff.Instance.UpdateSensor(sensor, data);
                         }
                         else if (messageObject.GetNamedString("type") == "UIaction")
                         {
                             //send action to buttons
                             string button = messageObject.GetNamedString("id");
                             string data   = messageObject.GetNamedString("data");
                             UpdateStuff.Instance.UpdateButton(button, data);
                         }
                     }
                 }
             }
             catch (Exception e)
             {
                 //this should catch bad format messages or Unity related errors
                 Debug.Log(e.Message);
             }
         }
     }
     catch (Exception ex)
     {
         Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult);
         Debug.Log(ex);
         //close the websocket
         this.messageWebSocket.Close(1006, ex.Message);
         //create a new one and reconnect
         this.Initialize();
     }
 }
        private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            try
            {
                using (DataReader reader = args.GetDataReader())
                {
                    reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                    byte[] read = new byte[reader.UnconsumedBufferLength];
                    reader.ReadBytes(read);
                    try
                    {
                        WebSocketMessage message = WebSocketMessage.ParseFrom(read);

                        Debug.WriteLine("Message Type: " + message.Type);

                        if (message.Type == WebSocketMessage.Types.Type.REQUEST)
                        {
                            incomingRequests.AddFirst(message.Request);
                            MessageReceived(this, message.Request);
                        }

                        
                    }
                    catch (InvalidProtocolBufferException e)
                    {
                        Debug.WriteLine(e.Message);
                    }

                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #34
0
    private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (Windows.Storage.Streams.DataReader dataReader = args.GetDataReader())
            {
                dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                string message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                Debug.Log("Message received from MessageWebSocket: " + message);
                cmds.Enqueue(message);
                //m_Socket.Dispose();
            }
        }
        catch (Exception ex)
        {
            Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult);
            // Add additional code here to handle exceptions.
        }

    }