public GetDataReader ( ) : |
||
return |
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 }); }
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); } }
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(); } }
//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); } } }
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. } }
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); } } }); }
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 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); } }
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"); } }
/// <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 Connection_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { try { using (var dr = args.GetDataReader()) { dr.UnicodeEncoding = UnicodeEncoding.Utf8; var message = dr.ReadString(dr.UnconsumedBufferLength); var obj = JsonConvert.DeserializeObject<dynamic>(message); var id = (string)obj.id; var type = (string)obj.type; TaskCompletionSource<dynamic> taskCompletion; if (type == "registered") { if (_tokens.TryRemove(id, out taskCompletion)) { var key = (string)JObject.Parse(message)["payload"]["client-key"]; taskCompletion.TrySetResult(new { clientKey = key }); } } else if (_tokens.TryGetValue(id, out taskCompletion)) { if (id == "register_0") return; if (obj.type == "error") { taskCompletion.SetException(new Exception(obj.error)); } //else if (args.Cancelled) //{ // taskSource.SetCanceled(); //} taskCompletion.TrySetResult(obj.payload); } } } catch (Exception ex) { WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult); } }
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); } } }
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); } }
/// <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); } }
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 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 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 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_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 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"); } }
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); }
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); } }
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 { } }