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); } } }
public MopidyClient() { socket = new MessageWebSocket(); socket.Control.MessageType = SocketMessageType.Utf8; socket.Closed += (senderSocket, args) => { // DO SOMETHING }; socket.MessageReceived += (sender, args) => { using (var reader = args.GetDataReader()) { reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string resultString = reader.ReadString(reader.UnconsumedBufferLength); JsonObject message; if (JsonObject.TryParse(resultString, out message)) { IJsonValue idValue; if (message.TryGetValue("id", out idValue)) { double id = idValue.GetNumber(); Action<JsonObject> callback; if (callbacks.TryGetValue(id, out callback)) { callback(message); } } } } }; messageWriter = new DataWriter(socket.OutputStream); }
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { if (args.ShareOperation.Data.Contains(StandardDataFormats.WebLink)) { Uri uri = await args.ShareOperation.Data.GetWebLinkAsync(); if (null != uri) try { using (var socket = new MessageWebSocket()) { socket.Control.MessageType = SocketMessageType.Utf8; await socket.ConnectAsync(new Uri("ws://" + settings["Host"].ToString() + ":" + settings["Port"].ToString())); using (var writer = new DataWriter(socket.OutputStream)) { writer.WriteString(uri.AbsoluteUri); await writer.StoreAsync(); args.ShareOperation.ReportCompleted(); } } } catch { show(); } } }
public void Dispose() { messageWriter?.Dispose(); messageWriter = null; socket?.Dispose(); socket = null; }
// WebSockets Button private async void Button_Click(object sender, RoutedEventArgs e) { try { //creates a new MessageWebSocket and connects to WebSocket server and sends data to server //Make a local copy MessageWebSocket webSocket = messageWebSocket; //Have we connected yet? if (webSocket == null) { Uri server = new Uri(ServerAddressField.Text.Trim()); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; messageWriter = new DataWriter(webSocket.OutputStream); } //InputField is a textbox in the xaml string message = InputField.Text; messageWriter.WriteString(message); await messageWriter.StoreAsync(); } catch (Exception ex) { String.Format("There is an error in connection"); } }
protected void Initialize() { #if WINDOWS_UWP this.messageWebSocket = new Windows.Networking.Sockets.MessageWebSocket(); // In this example, we send/receive a string, so we need to set the MessageType to Utf8. this.messageWebSocket.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8; this.messageWebSocket.MessageReceived += WebSocket_MessageReceived; this.messageWebSocket.Closed += WebSocket_Closed; try { Debug.Log("will connect"); Task connectTask = this.messageWebSocket.ConnectAsync(new Uri("ws://52.90.235.79:6789")).AsTask(); connectTask.ContinueWith(_ => this.Send("message", "hello")); //this.SendMessageUsingMessageWebSocketAsync("{\"message\": \"hello\"}")); //socketConnected = true; //Debug.Log("now connected."); } catch (Exception ex) { Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add additional code here to handle exceptions. Debug.Log(ex); } #endif }
public async Task Connect() { if (!_isLoggedIn) throw new DiscordException(ExceptionList.NotLoggedIn); _socket = new MessageWebSocket(); _writer = new DataWriter(_socket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8 }; _socket.Control.MessageType = SocketMessageType.Utf8; _socket.MessageReceived += socket_MessageReceived; string gatewayUrl = await GetGateway(); await _socket.ConnectAsync(new Uri(gatewayUrl)); JsonObject request = new JsonObject { { "op", JsonValue.CreateNumberValue(2) }, { "d", new JsonObject { { "token", JsonValue.CreateStringValue(_token) }, { "v", JsonValue.CreateNumberValue(3) }, { "properties", new JsonObject { { "$os", JsonValue.CreateStringValue("Windows") } }}, { "large_threshold", JsonValue.CreateNumberValue(0) } } } }; await WriteToSocket(request.Stringify()); }
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 }); }
public void connect(string url, string[] protocols, JObject options, int id) { var webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; if (protocols != null) { foreach (var protocol in protocols) { webSocket.Control.SupportedProtocols.Add(protocol); } } if (options != null && options.ContainsKey("origin")) { throw new NotImplementedException(/* TODO: (#253) */); } webSocket.MessageReceived += (sender, args) => { OnMessageReceived(id, sender, args); }; webSocket.Closed += (sender, args) => { OnClosed(id, sender, args); }; InitializeInBackground(id, url, webSocket); }
public async Task<bool> Connect(Uri uri, bool ignoreReceiver = false) { try { _commandCount = 0; _connection = new MessageWebSocket(); _connection.Control.MessageType = SocketMessageType.Utf8; // if(ignoreReceiver==false) _connection.MessageReceived += Connection_MessageReceived; _connection.Closed += Connection_Closed; await _connection.ConnectAsync(uri); IsConnected?.Invoke(true); _messageWriter = new DataWriter(_connection.OutputStream); return true; } catch (Exception e) { switch (SocketError.GetStatus(e.HResult)) { case SocketErrorStatus.HostNotFound: // Handle HostNotFound Error break; default: // Handle Unknown Error break; } return false; } }
public IEnumerator Connect() { #endif #if !UNITY_EDITOR m_Socket = new Windows.Networking.Sockets.MessageWebSocket(); // In this example, we send/receive a string, so we need to set the MessageType to Utf8. m_Socket.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8; m_Socket.MessageReceived += WebSocket_MessageReceived; m_Socket.Closed += WebSocket_Closed; try { Task connectTask = m_Socket.ConnectAsync(new Uri(mUrl.ToString())).AsTask(); // connectTask.ContinueWith(_ => this.SendMessageUsingMessageWebSocketAsync("Hello, World!")); } catch (Exception ex) { Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult); // Add additional code here to handle exceptions. FlowNetworkManager.log(ex.Message); } yield return 0; }
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); } }
/// <summary> /// Initializes a new instance of the <see cref="WebSocketConnection"/> class. /// </summary> /// <param name="serverUri"> /// The server uri. /// </param> public WebSocketConnection(Uri serverUri) { this.serverUri = serverUri; this.messageWebSocket = new MessageWebSocket(); this.sendQueue = new BlockingCollection<string>(); this.receiveQueue = new BlockingCollection<string>(); }
public WebSocketJavaScriptExecutor() { _webSocket = new MessageWebSocket(); _webSocket.Control.MessageType = SocketMessageType.Utf8; _webSocket.MessageReceived += OnMessageReceived; _webSocket.Closed += OnClosed; _injectedObjects = new JObject(); _callbacks = new Dictionary<int, TaskCompletionSource<JToken>>(); }
public MessageWebSocketTransport() { this._socket = new MessageWebSocket(); this._serializer = new DapperWare.Serialization.JsonSerializer(); this._socket.Control.SupportedProtocols.Add("wamp"); this._socket.MessageReceived += _socket_MessageReceived; this._socket.Closed += _socket_Closed; }
private void Closed(IWebSocket sender, WebSocketClosedEventArgs args) { System.Diagnostics.Debug.WriteLine("Closed; Code: " + args.Code + ", Reason: " + args.Reason); if (messageWebSocket != null) { messageWebSocket.Dispose(); messageWebSocket = null; } }
public WebSocketNativeImplImpl() { dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { sck = new Windows.Networking.Sockets.MessageWebSocket(); sck.MessageReceived += Sck_MessageReceived; sck.Closed += Sck_Closed; }).AsTask().GetAwaiter().GetResult(); }
private void Cleanup() { if (webSocket != null) { writer.Dispose(); writer = null; webSocket.Dispose(); webSocket = null; users.Clear(); } }
public MainWindow() { InitializeComponent(); serverIsDead = false; client = new HttpClient(); webSocket = null; writer = null; users = new List<SlackUser>(); Uri url = new Uri("https://slack.com/oauth/authorize?client_id=" + Secrets.SlackClientId + "&scope=client"); urlBox.Text = url.ToString(); }
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 async Task SetupWebsocket() { this._messageWebSocket = new Windows.Networking.Sockets.MessageWebSocket(); this._messageWebSocket.MessageReceived += WebSocket_MessageReceived; this._messageWebSocket.Closed += WebSocket_Closed; await this._messageWebSocket.ConnectAsync(new Uri("ws://" + Const.SERVER_IP + ":" + Const.PORT)); StartVideoStreamingThread(); }
public void Open(string url) { receiveQueue.Clear(); Dispose(); try { socket = new MessageWebSocket(); socket.Control.MessageType = SocketMessageType.Binary; socket.MessageReceived += (s, e) => { try { using (var reader = e.GetDataReader()) { var buf = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(buf); if (e.MessageType == SocketMessageType.Binary) { Debug.WriteLine("WebSocket MessageReceived(binary): length=" + buf.Length); lock (syncRoot) { receiveQueue.Enqueue(buf); } } else { Debug.WriteLine("WebSocket MessageReceived(text): " + Encoding.UTF8.GetString(buf, 0, buf.Length)); } } } catch (Exception ex) { Connected = false; var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("WebSocket MessageReceived Error: " + status); } }; socket.Closed += (s, e) => Debug.WriteLine("WebSocket Closed"); socket.ConnectAsync(new Uri(url)).AsTask().Wait(); Connected = true; Debug.WriteLine("WebSocket Opened"); writer = new DataWriter(socket.OutputStream); } catch (Exception ex) { Connected = false; var status = WebSocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("WebSocket Open Error: " + status); } }
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); } } }
//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 void CloseSocket() { if (this.messageWebSocket != null) { try { this.messageWebSocket.Close(1000, "Closed due to user request."); } catch (Exception e) { Debug.Log(e.Message); } this.messageWebSocket = null; } }
private async Task StartWebSocket(IConnection connection, string url) { var uri = UrlBuilder.ConvertToWebSocketUri(url); connection.Trace(TraceLevels.Events, "WS Connecting to: {0}", uri); if (_webSocket == null) { var webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.Closed += WebsocketClosed; webSocket.MessageReceived += MessageReceived; connection.PrepareRequest(new WebSocketRequest(webSocket)); await OpenWebSocket(webSocket, uri); _webSocket = webSocket; } }
public bool CloseWebSocket() { bool worked = false; if(webSocket != null) { try { webSocket.Close(0, "App Closing"); worked = true; } catch (Exception) { } webSocket = null; } return worked; }
public async Task<bool> SetupWebSocket() { bool worked = false; try { ServerListItem server = settings.GetServer(); if (server == null) { return false; //throw new Exception("Server not set"); } Uri serverUri = new Uri("ws://" + server + "/mediabrowser"); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(serverUri); DataWriter messageWriter = new DataWriter(webSocket.OutputStream); string deviceName = settings.GetDeviceName(); string value = "SPMB"; if (string.IsNullOrEmpty(deviceName) == false) { value = "SPMB-" + settings.GetDeviceName(); } string identityMessage = "{\"MessageType\":\"Identity\", \"Data\":\"Windows RT|" + settings.GetDeviceId() + "|0.0.1|" + value + "\"}"; messageWriter.WriteString(identityMessage); await messageWriter.StoreAsync(); worked = true; } catch(Exception e) { MetroEventSource.Log.Info("Error Creating WebSocket - " + e.Message); string errorString = "Error Creating WebSocket : " + e.Message; App.AddNotification(new Notification() { Title = "Error Creating Web Socket", Message = errorString }); } return worked; }
public async void connect() { Debug.WriteLine("WSC connect()..."); if (socket == null) { socket = new MessageWebSocket(); if (userAgent != null) socket.SetRequestHeader("X-Signal-Agent", userAgent); socket.MessageReceived += OnMessageReceived; socket.Closed += OnClosed; try { Uri server = new Uri(wsUri); await socket.ConnectAsync(server); //Connected(this, EventArgs.Empty); keepAliveTimer = new Timer(sendKeepAlive, null, TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS), TimeSpan.FromSeconds(KEEPALIVE_TIMEOUT_SECONDS)); messageWriter = new DataWriter(socket.OutputStream); } catch (Exception e) { WebErrorStatus status = WebSocketError.GetStatus(e.GetBaseException().HResult); switch (status) { case WebErrorStatus.CannotConnect: case WebErrorStatus.NotFound: case WebErrorStatus.RequestTimeout: Debug.WriteLine("Cannot connect to the server. Please make sure " + "to run the server setup script before running the sample."); break; case WebErrorStatus.Unknown: throw; default: Debug.WriteLine("Error: " + status); break; } } Debug.WriteLine("WSC connected..."); } }
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"); } }
public void Open(string url, string protocol = null, string authToken = null) { try { if (_websocket != null) EndConnection(); _websocket = new MessageWebSocket(); _websocket.Control.MessageType = SocketMessageType.Utf8; _websocket.Closed += _websocket_Closed; _websocket.MessageReceived += _websocket_MessageReceived; if (url.StartsWith("https")) url = url.Replace("https://", "wss://"); else if (url.StartsWith("http")) url = url.Replace("http://", "ws://"); if (authToken != null) { _websocket.SetRequestHeader("Authorization", authToken); } _websocket.ConnectAsync(new Uri(url)).Completed = (source, status) => { if (status == AsyncStatus.Completed) { messageWriter = new DataWriter(_websocket.OutputStream); IsOpen = true; OnOpened(); } else if (status == AsyncStatus.Error) { OnError("Websocket error"); } }; } catch (Exception ex) { OnError(ex.Message); } }
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. } }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); CheckValidState(s_validConnectingStates); _messageWebSocket = new MessageWebSocket(); foreach (var header in options.RequestHeaders) { _messageWebSocket.SetRequestHeader((string)header, options.RequestHeaders[(string)header]); } string cookies = options.Cookies == null ? null : options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookies)) { _messageWebSocket.SetRequestHeader(HeaderNameCookie, cookies); } var websocketControl = _messageWebSocket.Control; foreach (var subProtocol in options.RequestedSubProtocols) { websocketControl.SupportedProtocols.Add(subProtocol); } try { _receiveAsyncBufferTcs = new TaskCompletionSource<ArraySegment<byte>>(); _closeWebSocketReceiveResultTcs = new TaskCompletionSource<WebSocketReceiveResult>(); _messageWebSocket.MessageReceived += OnMessageReceived; _messageWebSocket.Closed += OnCloseReceived; await _messageWebSocket.ConnectAsync(uri).AsTask(cancellationToken); _subProtocol = _messageWebSocket.Information.Protocol; _messageWriter = new DataWriter(_messageWebSocket.OutputStream); } catch (Exception) { UpdateState(WebSocketState.Closed); throw; } UpdateState(WebSocketState.Open); }
private void CreateSocket() { ws = new MessageWebSocket(); ws.Control.MessageType = SocketMessageType.Utf8; ws.MessageReceived += (sender, args) => { string read; using (var reader = args.GetDataReader()) { reader.UnicodeEncoding = global::Windows.Storage.Streams.UnicodeEncoding.Utf8; read = reader.ReadString(reader.UnconsumedBufferLength); //Debug.WriteLine("{0} : {1} : {2}", DateTime.Now, "received", read); } OnMessage(read); }; ws.Closed += (sender, args) => { }; }
async void SensorValueChanged(object sender, X2CodingLab.SensorTag.SensorValueChangedEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { switch (e.Origin) { case SensorName.Accelerometer: // WebSockets MessageWebSocket webSocket = messageWebSocket; if (webSocket == null) { Uri server = new Uri("ws://localhost:8181"); webSocket = new MessageWebSocket(); webSocket.Control.MessageType = SocketMessageType.Utf8; webSocket.MessageReceived += MessageReceived; webSocket.Closed += Closed; await webSocket.ConnectAsync(server); messageWebSocket = webSocket; messageWriter = new DataWriter(webSocket.OutputStream); } string message = null; //byte[] accValue = await acc.ReadValue(); double[] accAxis = Accelerometer.CalculateCoordinates(e.RawData, 1 / 64.0); double xRaw = accAxis[0] / 4; double yRaw = accAxis[1] / 4; message = "SET RAW_INPUT " + xRaw.ToString("0.00000") + "," + yRaw.ToString("0.00000"); info.Text = message; messageWriter.WriteString(message); await messageWriter.StoreAsync(); break; } }); }
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); } }
public void disconnect() { Debug.WriteLine("WSC disconnect()..."); if (socket != null) { socket.Close(1000, "None"); socket = null; } /*if (keepAliveSender != null) { keepAliveSender.shutdown(); keepAliveSender = null; }*/ }