public static void EchoClient() { Console.WriteLine("Starting EKE WSS connection"); //string hostWithProtocolAndPort = "ws://*****:*****@gmail.com"; string idParam = "groupID=4ddf4bef-0f60-41b6-925d-02721e89d637"; string deviceConnectionUrl = hostWithProtocolAndPort + "/websocket/NegotiateDeviceConnection?" + idParam; //socket = new WebSocket("wss://theball.protonit.net/websocket/mytest.k"); string sharedSecret = "testsecretXYZ33"; var securityNegotiationManager = InitSecurityNegotiationManager(deviceConnectionUrl, Encoding.UTF8.GetBytes(sharedSecret), "test device desc", false); securityNegotiationManager.PerformNegotiation(); #if native45 //WebSocket socket = new ClientWebSocket(); //WebSocket.CreateClientWebSocket() ClientWebSocket socket = new ClientWebSocket(); Uri uri = new Uri("ws://localhost:50430/websocket/mytest.k"); var cts = new CancellationTokenSource(); await socket.ConnectAsync(uri, cts.Token); Console.WriteLine(socket.State); Task.Factory.StartNew( async () => { var rcvBytes = new byte[128]; var rcvBuffer = new ArraySegment<byte>(rcvBytes); while (true) { WebSocketReceiveResult rcvResult = await socket.ReceiveAsync(rcvBuffer, cts.Token); byte[] msgBytes = rcvBuffer.Skip(rcvBuffer.Offset).Take(rcvResult.Count).ToArray(); string rcvMsg = Encoding.UTF8.GetString(msgBytes); Console.WriteLine("Received: {0}", rcvMsg); } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); while (true) { var message = Console.ReadLine(); if (message == "Bye") { cts.Cancel(); return; } byte[] sendBytes = Encoding.UTF8.GetBytes(message); var sendBuffer = new ArraySegment<byte>(sendBytes); await socket.SendAsync(sendBuffer, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: cts.Token); } #endif }
public async Task ConnectAsync_AddCustomHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { cws.Options.SetRequestHeader("X-CustomHeader1", "Value1"); cws.Options.SetRequestHeader("X-CustomHeader2", "Value2"); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; var segment = new ArraySegment<byte>(buffer, 0, buffer.Length); WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await cws.ReceiveAsync(segment, cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(segment); Assert.True(headers.Contains("X-CustomHeader1:Value1")); Assert.True(headers.Contains("X-CustomHeader2:Value2")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } }
private static bool InitWebSocketSupported() { ClientWebSocket cws = null; try { cws = new ClientWebSocket(); return true; } catch (PlatformNotSupportedException) { return false; } finally { if (cws != null) { cws.Dispose(); } } }
public static async Task<ClientWebSocket> GetConnectedWebSocket( Uri server, int timeOutMilliseconds, ITestOutputHelper output, TimeSpan keepAliveInterval = default(TimeSpan)) { const int MaxTries = 5; int betweenTryDelayMilliseconds = 1000; for (int i = 1; ; i++) { try { var cws = new ClientWebSocket(); if (keepAliveInterval.TotalSeconds > 0) { cws.Options.KeepAliveInterval = keepAliveInterval; } using (var cts = new CancellationTokenSource(timeOutMilliseconds)) { output.WriteLine("GetConnectedWebSocket: ConnectAsync starting."); Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open) || (cws.State == WebSocketState.Aborted), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; output.WriteLine("GetConnectedWebSocket: ConnectAsync done."); Assert.Equal(WebSocketState.Open, cws.State); } return cws; } catch (WebSocketException exc) { output.WriteLine($"Retry after attempt #{i} failed with {exc}"); if (i == MaxTries) { throw; } await Task.Delay(betweenTryDelayMilliseconds); betweenTryDelayMilliseconds *= 2; } } }
public void Dispose_CreateAndDispose_ExpectedPropertyValues() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); }
public void Ctor_Success() { var cws = new ClientWebSocket(); cws.Dispose(); }
public void CloseAsync_CreateAndClose_ThrowsInvalidOperationException() { var cws = new ClientWebSocket(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.None, cws.State); }
public static void UseDefaultCredentials_Roundtrips() { var cws = new ClientWebSocket(); Assert.False(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = true; Assert.True(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = false; Assert.False(cws.Options.UseDefaultCredentials); }
public void CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithCorrectMessage() { var cws = new ClientWebSocket(); AssertExtensions.Throws<InvalidOperationException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(), ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected")); Assert.Equal(WebSocketState.None, cws.State); }
public static void SetBuffer_InvalidArgs_Throws() { var cws = new ClientWebSocket(); Assert.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0)); Assert.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 1)); Assert.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0, new ArraySegment<byte>(new byte[1]))); Assert.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 1, new ArraySegment<byte>(new byte[1]))); Assert.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(1, 0, new ArraySegment<byte>(new byte[1]))); Assert.Throws<ArgumentNullException>("buffer.Array", () => cws.Options.SetBuffer(1, 1, default(ArraySegment<byte>))); Assert.Throws<ArgumentOutOfRangeException>("buffer", () => cws.Options.SetBuffer(1, 1, new ArraySegment<byte>(new byte[0]))); }
public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationException() { var cws = new ClientWebSocket(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.ReceiveAsync(segment, ct); }); Assert.Equal(WebSocketState.None, cws.State); }
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(server, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } }
public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithCorrectMessage() { var cws = new ClientWebSocket(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); AssertExtensions.Throws<InvalidOperationException>( () => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(), ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected")); Assert.Equal(WebSocketState.None, cws.State); }
public static void KeepAliveInterval_Roundtrips() { var cws = new ClientWebSocket(); Assert.True(cws.Options.KeepAliveInterval > TimeSpan.Zero); cws.Options.KeepAliveInterval = TimeSpan.Zero; Assert.Equal(TimeSpan.Zero, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = TimeSpan.MaxValue; Assert.Equal(TimeSpan.MaxValue, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, cws.Options.KeepAliveInterval); Assert.Throws<ArgumentOutOfRangeException>("value", () => cws.Options.KeepAliveInterval = TimeSpan.MinValue); }
public async Task ConnectAsync_Cancel_ThrowsWebSocketExceptionWithMessage(Uri server) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(500); var ub = new UriBuilder(server); ub.Query = "delay10sec"; WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token)); Assert.Equal( ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); } }
public void Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server) { using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "delay10sec"; Task t = cws.ConnectAsync(ub.Uri, cts.Token); cws.Abort(); WebSocketException ex = Assert.Throws<WebSocketException>(() => t.GetAwaiter().GetResult()); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); } }
public static async Task<ClientWebSocket> GetConnectedWebSocket( Uri server, int timeOutMilliseconds, ITestOutputHelper output) { var cws = new ClientWebSocket(); var cts = new CancellationTokenSource(timeOutMilliseconds); output.WriteLine("GetConnectedWebSocket: ConnectAsync starting."); Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( (cws.State == WebSocketState.None) || (cws.State == WebSocketState.Connecting) || (cws.State == WebSocketState.Open), "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; output.WriteLine("GetConnectedWebSocket: ConnectAsync done."); Assert.Equal(WebSocketState.Open, cws.State); return cws; }
public async Task ConnectAsync_CookieHeaders_Success(Uri server) { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.Cookies); cws.Options.Cookies = new CookieContainer(); cws.Options.Cookies.Add(server, new Cookie("Cookies", "Are Yummy")); cws.Options.Cookies.Add(server, new Cookie("Especially", "Chocolate Chip")); using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { Task taskConnect = cws.ConnectAsync(server, cts.Token); Assert.True( cws.State == WebSocketState.None || cws.State == WebSocketState.Connecting || cws.State == WebSocketState.Open, "State immediately after ConnectAsync incorrect: " + cws.State); await taskConnect; } Assert.Equal(WebSocketState.Open, cws.State); byte[] buffer = new byte[65536]; var segment = new ArraySegment<byte>(buffer); WebSocketReceiveResult recvResult; using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { recvResult = await cws.ReceiveAsync(segment, cts.Token); } Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType); string headers = WebSocketData.GetTextFromBuffer(segment); Assert.True(headers.Contains("Cookies=Are Yummy")); Assert.True(headers.Contains("Especially=Chocolate Chip")); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } }
public void CloseAsync_CreateAndSend_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.SendAsync(segment, WebSocketMessageType.Text, false, ct); }); Assert.Equal(WebSocketState.None, cws.State); } }
public void CloseAsync_DisposeAndClose_ThrowsObjectDisposedException() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.Closed, cws.State); }
private void CreateSocket() { WebSocket = new ClientWebSocket(); WebSocket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); }
public FastProtobufProxy() { ClientWebSocket = new ClientWebSocket(); ClientWebSocket.Options.KeepAliveInterval = TimeSpan.FromDays(30); }
public async Task OpenSocket() { Uri link = new Uri("wss://iotnet.teracom.dk/app?token=vnoTQQAAABFpb3RuZXQuY2liaWNvbS5ka45GqovHqK3PVCJypYVMsIw="); var ws = new ClientWebSocket(); Console.WriteLine("Connecting ..."); ws.ConnectAsync(link, CancellationToken.None).Wait(); //Send cache request /*String request= "{\"cmd\":\"cq\",\"page\":1,\"perPage\":100}"; * byte[] bytes = Encoding.ASCII.GetBytes(request); * Console.WriteLine("Sending cache request ..."); * ws.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None).Wait();*/ try { using (var ms = new MemoryStream()) { Console.WriteLine("Listening ..."); while (ws.State == WebSocketState.Open) { WebSocketReceiveResult result; //Loop until a message is received do { //Listen for incomming messages var messageBuffer = WebSocket.CreateClientBuffer(1024, 16); result = await ws.ReceiveAsync(messageBuffer, CancellationToken.None); ms.Write(messageBuffer.Array, messageBuffer.Offset, result.Count); }while (!result.EndOfMessage); if (result.MessageType == WebSocketMessageType.Text) { var msgString = Encoding.UTF8.GetString(ms.ToArray()); //Is the cache response is received /*if(msgString.Substring(8,2) == "cq") * { * Console.WriteLine("Cache message received."); * SaveCacheMessage(msgString); * }*/ //If Sensors send a signal if (msgString.Substring(8, 2) == "gw") { Console.WriteLine("Sensor message received."); Console.WriteLine(msgString); SaveMessage(msgString); } } //Reset the memory stream back to start ms.Seek(0, SeekOrigin.Begin); ms.Position = 0; ms.SetLength(0); } Console.WriteLine("Restarting socket connection"); OpenSocket(); } } catch (InvalidOperationException) { Console.WriteLine("Oopsie ..."); } }
protected void InitConnectionBase(ClientWebSocket socket) { Ensure.NotNull(socket, "socket"); _socket = socket; }
public ClientWebSocketWrapper(ClientWebSocket clientWebSocket) : base(clientWebSocket) { mClientWebSocket = clientWebSocket; }
public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server) { const string AcceptedProtocol = "AcceptedProtocol"; const string OtherProtocol = "OtherProtocol"; using (var cws = new ClientWebSocket()) { cws.Options.AddSubProtocol(AcceptedProtocol); cws.Options.AddSubProtocol(OtherProtocol); var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; await cws.ConnectAsync(ub.Uri, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); Assert.Equal(AcceptedProtocol, cws.SubProtocol); } }
public override async Task Handle(HttpContext context) { ClientWebSocket wsServer = null; System.Net.WebSockets.WebSocket wsClient = null; try { // First we need the URL for this connection, since it's been requested to be upgraded to // a websocket. var fullUrl = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(context.Request); // Need to replate the scheme with appropriate websocket scheme. if (fullUrl.StartsWith("http://")) { fullUrl = "ws://" + fullUrl.Substring(7); } else if (fullUrl.StartsWith("https://")) { fullUrl = "wss://" + fullUrl.Substring(8); } // Next we need to try and parse the URL as a URI, because the websocket client requires // this for connecting upstream. if (!Uri.TryCreate(fullUrl, UriKind.RelativeOrAbsolute, out Uri wsUri)) { LoggerProxy.Default.Error("Failed to parse websocket URI."); return; } // Create the websocket that's going to connect to the remote server. wsServer = new ClientWebSocket(); wsServer.Options.Cookies = new System.Net.CookieContainer(); wsServer.Options.SetBuffer((int)ushort.MaxValue * 16, (int)ushort.MaxValue * 16); foreach (var cookie in context.Request.Cookies) { try { wsServer.Options.Cookies.Add(new Uri(fullUrl, UriKind.Absolute), new System.Net.Cookie(cookie.Key, System.Net.WebUtility.UrlEncode(cookie.Value))); } catch (Exception e) { LoggerProxy.Default.Error("Error while attempting to add websocket cookie."); LoggerProxy.Default.Error(e); } } if (context.Connection.ClientCertificate != null) { wsServer.Options.ClientCertificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection(new[] { context.Connection.ClientCertificate.ToV2Certificate() }); } var reqHeaderBuilder = new StringBuilder(); foreach (var hdr in context.Request.Headers) { if (!ForbiddenWsHeaders.IsForbidden(hdr.Key)) { reqHeaderBuilder.AppendFormat("{0}: {1}\r\n", hdr.Key, hdr.Value.ToString()); try { wsServer.Options.SetRequestHeader(hdr.Key, hdr.Value.ToString()); Console.WriteLine("Set Header: {0} ::: {1}", hdr.Key, hdr.Value.ToString()); } catch (Exception hdrException) { Console.WriteLine("Failed Header: {0} ::: {1}", hdr.Key, hdr.Value.ToString()); LoggerProxy.Default.Error(hdrException); } } } reqHeaderBuilder.Append("\r\n"); LoggerProxy.Default.Info(string.Format("Connecting websocket to {0}", wsUri.AbsoluteUri)); // Connect the server websocket to the upstream, remote webserver. await wsServer.ConnectAsync(wsUri, context.RequestAborted); LoggerProxy.Default.Info(String.Format("Connected websocket to {0}", wsUri.AbsoluteUri)); // Create, via acceptor, the client websocket. This is the local machine's websocket. wsClient = await context.WebSockets.AcceptWebSocketAsync(wsServer.SubProtocol ?? null); ProxyNextAction nxtAction = ProxyNextAction.AllowAndIgnoreContentAndResponse; string customResponseContentType = string.Empty; byte[] customResponse = null; m_msgBeginCb?.Invoke(wsUri, reqHeaderBuilder.ToString(), null, context.Request.IsHttps ? MessageType.SecureWebSocket : MessageType.WebSocket, MessageDirection.Request, out nxtAction, out customResponseContentType, out customResponse); switch (nxtAction) { case ProxyNextAction.DropConnection: { if (customResponse != null) { } await wsClient.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); return; } } // Spawn an async task that will poll the remote server for data in a loop, and then // write any data it gets to the client websocket. var serverTask = Task.Run(async() => { System.Net.WebSockets.WebSocketReceiveResult serverStatus = null; var serverBuffer = new byte[1024 * 4]; try { bool looping = true; serverStatus = await wsServer.ReceiveAsync(new ArraySegment <byte>(serverBuffer), context.RequestAborted); while (looping && !serverStatus.CloseStatus.HasValue && !context.RequestAborted.IsCancellationRequested) { await wsClient.SendAsync(new ArraySegment <byte>(serverBuffer, 0, serverStatus.Count), serverStatus.MessageType, serverStatus.EndOfMessage, context.RequestAborted); if (!wsClient.CloseStatus.HasValue) { serverStatus = await wsServer.ReceiveAsync(new ArraySegment <byte>(serverBuffer), context.RequestAborted); continue; } looping = false; } await wsClient.CloseAsync(serverStatus.CloseStatus.Value, serverStatus.CloseStatusDescription, context.RequestAborted); } catch { try { var closeStatus = serverStatus?.CloseStatus ?? System.Net.WebSockets.WebSocketCloseStatus.NormalClosure; var closeMessage = serverStatus?.CloseStatusDescription ?? string.Empty; await wsClient.CloseAsync(closeStatus, closeMessage, context.RequestAborted); } catch { } } }); // Spawn an async task that will poll the local client websocket, in a loop, and then // write any data it gets to the remote server websocket. var clientTask = Task.Run(async() => { System.Net.WebSockets.WebSocketReceiveResult clientResult = null; var clientBuffer = new byte[1024 * 4]; try { bool looping = true; clientResult = await wsClient.ReceiveAsync(new ArraySegment <byte>(clientBuffer), context.RequestAborted); while (looping && !clientResult.CloseStatus.HasValue && !context.RequestAborted.IsCancellationRequested) { await wsServer.SendAsync(new ArraySegment <byte>(clientBuffer, 0, clientResult.Count), clientResult.MessageType, clientResult.EndOfMessage, context.RequestAborted); if (!wsServer.CloseStatus.HasValue) { clientResult = await wsClient.ReceiveAsync(new ArraySegment <byte>(clientBuffer), context.RequestAborted); continue; } looping = false; } await wsServer.CloseAsync(clientResult.CloseStatus.Value, clientResult.CloseStatusDescription, context.RequestAborted); } catch { try { var closeStatus = clientResult?.CloseStatus ?? System.Net.WebSockets.WebSocketCloseStatus.NormalClosure; var closeMessage = clientResult?.CloseStatusDescription ?? string.Empty; await wsServer.CloseAsync(closeStatus, closeMessage, context.RequestAborted); } catch { } } }); // Above, we have created a bridge between the local and remote websocket. Wait for both // associated tasks to complete. await Task.WhenAll(serverTask, clientTask); } catch (Exception wshe) { if (wshe is System.Net.WebSockets.WebSocketException) { var cast = wshe as System.Net.WebSockets.WebSocketException; Console.WriteLine(cast.WebSocketErrorCode); if (cast.Data != null) { foreach (KeyValuePair <object, object> kvp in cast.Data) { Console.WriteLine("{0} ::: {1}", kvp.Key, kvp.Value); } } } LoggerProxy.Default.Error(wshe); } finally { if (wsClient != null) { wsClient.Dispose(); wsClient = null; } if (wsServer != null) { wsServer.Dispose(); wsServer = null; } } }
/// <summary>Runs the application. Retrives a token from the authentication server, then opens /// the WebSocket using the token.</summary> public void Run() { /* Get local hostname. */ IPAddress hostEntry = Array.Find(Dns.GetHostEntry(Dns.GetHostName()).AddressList, ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); _position = (hostEntry == null) ? "127.0.0.1/net" : hostEntry.ToString(); /* Open a websocket. */ Uri uri = new Uri("wss://" + _hostName + ":" + _port + "/WebSocket"); Console.WriteLine("Connecting to WebSocket " + uri.AbsoluteUri + " ..."); if (!GetAuthenticationInfo(false)) { Environment.Exit(1); } _webSocket = new ClientWebSocket(); _webSocket.Options.SetBuffer(BUFFER_SIZE, BUFFER_SIZE); _webSocket.Options.AddSubProtocol("tr_json2"); Console.CancelKeyPress += Console_CancelKeyPress; try { _webSocket.ConnectAsync(uri, CancellationToken.None).Wait(); if (_webSocket.State == WebSocketState.Open) { SendLogin(false); /* Run a take to read messages */ Task.Factory.StartNew(() => { while (_webSocket.State == WebSocketState.Open) { try { ReceiveMessage(); } catch (System.AggregateException) { System.Console.WriteLine("The WebSocket connection is closed"); Console_CancelKeyPress(null, null); } } }); while (true) { Thread.Sleep((int)(_expirationInMilliSeconds * .90)); if (_loggedIn) { if (!GetAuthenticationInfo(true)) { Environment.Exit(1); } if (_expirationInMilliSeconds != _originalExpirationInMilliSeconds) { System.Console.WriteLine("expire time changed from " + _originalExpirationInMilliSeconds / 1000 + " sec to " + _expirationInMilliSeconds / 1000 + " sec; retry with password"); if (!GetAuthenticationInfo(false)) { Environment.Exit(1); } } SendLogin(true); } if (_webSocket.State == WebSocketState.Aborted) { System.Console.WriteLine("The WebSocket connection is closed"); Console_CancelKeyPress(null, null); break; } } } else { System.Console.WriteLine("Failed to open a WebSocket connection"); } } catch (Exception ex) { System.Console.WriteLine(ex); } finally { Console_CancelKeyPress(this, null); } }
Func <IPAddress, int, Task <IChannel> > CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings) { return(async(address, port) => { var additionalQueryParams = ""; #if WINDOWS_UWP // UWP implementation doesn't set client certs, so we want to tell the IoT Hub to not ask for them additionalQueryParams = "?iothub-no-client-cert=true"; #endif IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey); var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix + additionalQueryParams); var websocket = new ClientWebSocket(); websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt); #if !WINDOWS_UWP // UWP does not support proxies // Check if we're configured to use a proxy server IWebProxy webProxy = WebRequest.DefaultWebProxy; Uri proxyAddress = webProxy?.GetProxy(websocketUri); if (!websocketUri.Equals(proxyAddress)) { // Configure proxy server websocket.Options.Proxy = webProxy; } #endif if (settings.ClientCertificate != null) { websocket.Options.ClientCertificates.Add(settings.ClientCertificate); } #if !WINDOWS_UWP && !NETSTANDARD1_3 // UseDefaultCredentials is not in UWP and NetStandard else { websocket.Options.UseDefaultCredentials = true; } #endif using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1))) { await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token); } #if WINDOWS_UWP PlatformProvider.Platform = new UWPPlatform(); #endif var clientChannel = new ClientWebSocketChannel(null, websocket); clientChannel .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .Option(ChannelOption.AutoRead, false) .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator()) .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default) .Pipeline.AddLast( MqttEncoder.Instance, new MqttDecoder(false, MaxMessageSize), this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings)); await eventLoopGroup.GetNext().RegisterAsync(clientChannel); this.ScheduleCleanup(() => { EventLoopGroupPool.Release(this.eventLoopGroupKey); return TaskConstants.Completed; }); return clientChannel; }); }
public static void ConnectAll(bool first) { try { StatusText = "Connecting..."; Console.WriteLine("Connecting..."); FailedConnections.Clear(); var allSocketIps = Borsa.Sockets.ToList(); lock (Locker) { isLocked = true; StatusText = "Started connecting..."; //dc all children int j = 1; foreach (var child in Children.ToList()) { //Children.Remove(child); StatusText = "Disconnecting old sockets... " + j++; try { child.Socket.CloseAsync(WebSocketCloseStatus.Empty, String.Empty, CancellationToken.None).Wait(); } catch (Exception e) { } //child.Dispose(true); } //dc aligned sockets foreach (var kvp in ChildrenByBorsa.ToArray()) { foreach (var child in kvp.Value) { try { child.Socket.CloseAsync(WebSocketCloseStatus.Empty, String.Empty, CancellationToken.None).Wait(); } catch (Exception e) { } //child.Dispose(false); } } if (first) { //connect all children again for (var i = 0; i < allSocketIps.Count; i++) { StatusText = $"Connecting... ({i + 1}/{allSocketIps.Count})"; var socketIp = allSocketIps[i]; ClientWebSocket socket = new ClientWebSocket(); try { socket.ConnectAsync(new Uri("wss://" + socketIp + "/ws"), CancellationToken.None) .Wait(); var childSocket = new ChildSocket(socket, IdCounter++, socketIp, Children); Children.Add(childSocket); KeepListening(childSocket); } catch (Exception e) { FailedConnections.Add(socketIp); } } } /* * //align sockets again * foreach (var kvp in ChildrenByBorsa.ToArray()) * { * var oldList = kvp.Value.ToList(); * //align new sockets * var listOfAlignedChildren = Children.Take(oldList.Count).ToList(); * var newList = new List<ChildSocket>(); * foreach (var child in listOfAlignedChildren) * { * Children.Remove(child); * newList.Add(child); * child.Owner = newList; * } * * ChildrenByBorsa[kvp.Key] = newList; * * //dc old aligned sockets * foreach (var child in oldList) * { * try * { * //child.Socket.CloseAsync(WebSocketCloseStatus.Empty, String.Empty, CancellationToken.None); * } * catch (Exception e) * { * } * child.Dispose(true); * } * } */ } isLocked = false; StatusText = $"Connected to {allSocketIps.Count - FailedConnections.Count} sockets"; Console.WriteLine("Connected"); } catch (Exception e) { StatusText = e.ToString(); } }
public WebSocketClient() { Socket = new ClientWebSocket(); Socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(120); Socket.Options.SetBuffer(1024, 1024); }
public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); }
private async Task SendMessage(ClientWebSocket webSocket, string message) { await webSocket.SendAsync(new ArraySegment <byte>(Encoding.ASCII.GetBytes(message)), WebSocketMessageType.Text, true, default); }
public async Task ReadWriteTest() { var websocket = new ClientWebSocket(); // Set SubProtocol to AMQPWSB10 websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10); var uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}"); await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false); using var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null); // Test Write API var args = new TransportAsyncCallbackArgs(); args.CompletedCallback = (TransportAsyncCallbackArgs args) => { if (args.BytesTransfered != s_byteArray.Length) { throw new InvalidOperationException("All the bytes sent were not transferred"); } if (args.Exception != null) { throw args.Exception; } }; args.SetBuffer(s_byteArray, 0, s_byteArray.Length); clientWebSocketTransport.WriteAsync(args); // Test Read API bool isReadComplete = false; args.CompletedCallback = (TransportAsyncCallbackArgs args) => { if (args.Exception != null) { throw args.Exception; } // Verify that data matches what was sent if (s_byteArray.Length != args.Count) { throw new InvalidOperationException("Expected " + s_byteArray.Length + " bytes in response"); } for (int i = 0; i < args.Count; i++) { if (s_byteArray[i] != args.Buffer[i]) { throw new InvalidOperationException("Response contents do not match what was sent"); } } isReadComplete = true; }; if (clientWebSocketTransport.ReadAsync(args)) { while (!isReadComplete) { await Task.Delay(s_oneSecond); } } // Once Read operation is complete, close websocket transport // Test Close API await clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false); }
Func <IPAddress[], int, Task <IChannel> > CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, ProductInfo productInfo) { return(async(address, port) => { string additionalQueryParams = ""; #if NETSTANDARD1_3 // NETSTANDARD1_3 implementation doesn't set client certs, so we want to tell the IoT Hub to not ask for them additionalQueryParams = "?iothub-no-client-cert=true"; #endif var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix + additionalQueryParams); var websocket = new ClientWebSocket(); websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt); // Check if we're configured to use a proxy server IWebProxy webProxy = settings.Proxy; try { if (webProxy != DefaultWebProxySettings.Instance) { // Configure proxy server websocket.Options.Proxy = webProxy; if (Logging.IsEnabled) { Logging.Info(this, $"{nameof(CreateWebSocketChannelFactory)} Setting ClientWebSocket.Options.Proxy"); } } } catch (PlatformNotSupportedException) { // .NET Core 2.0 doesn't support proxy. Ignore this setting. if (Logging.IsEnabled) { Logging.Error(this, $"{nameof(CreateWebSocketChannelFactory)} PlatformNotSupportedException thrown as .NET Core 2.0 doesn't support proxy"); } } if (settings.ClientCertificate != null) { websocket.Options.ClientCertificates.Add(settings.ClientCertificate); } using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1))) { await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token).ConfigureAwait(true); } var clientChannel = new ClientWebSocketChannel(null, websocket); clientChannel .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default) .Option(ChannelOption.AutoRead, false) .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator()) .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default) .Pipeline.AddLast( MqttEncoder.Instance, new MqttDecoder(false, MaxMessageSize), new LoggingHandler(LogLevel.DEBUG), this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo)); await s_eventLoopGroup.Value.RegisterAsync(clientChannel).ConfigureAwait(false); return clientChannel; }); }
public async Task TestDrawingTheGame() { var cts = new CancellationTokenSource(); var clientSocket1 = new ClientWebSocket(); var clientSocket2 = new ClientWebSocket(); await clientSocket1.ConnectAsync(utils.serverUrl, cts.Token); await clientSocket2.ConnectAsync(utils.serverUrl, cts.Token); var findMsg = new FindGameMessage() { Size = 3 }; await utils.SendThroughSocketAsync(clientSocket1, findMsg, cts.Token); await utils.SendThroughSocketAsync(clientSocket2, findMsg, cts.Token); var gameFoundMsg1 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket1); var gameFoundMsg2 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket2); ClientWebSocket firstPlayerSocket, secondPlayerSocket; if (gameFoundMsg1.IsClientTurn) { firstPlayerSocket = clientSocket1; secondPlayerSocket = clientSocket2; } else { firstPlayerSocket = clientSocket2; secondPlayerSocket = clientSocket1; } // X| | // | | // | | await utils.SendThroughSocketAsync(firstPlayerSocket, new MakeMoveMessage() { X = 0, Y = 0 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X| | // O| | // | | await utils.SendThroughSocketAsync(secondPlayerSocket, new MakeMoveMessage() { X = 0, Y = 1 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X| | // O| | // |X| await utils.SendThroughSocketAsync(firstPlayerSocket, new MakeMoveMessage() { X = 1, Y = 2 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X|O| // O| | // |x| await utils.SendThroughSocketAsync(secondPlayerSocket, new MakeMoveMessage() { X = 1, Y = 0 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X|O| // O| |X // |x| await utils.SendThroughSocketAsync(firstPlayerSocket, new MakeMoveMessage() { X = 2, Y = 1 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X|O| // O| |X // |x|O await utils.SendThroughSocketAsync(secondPlayerSocket, new MakeMoveMessage() { X = 2, Y = 2 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X|O| // O|X|X // |x|O await utils.SendThroughSocketAsync(firstPlayerSocket, new MakeMoveMessage() { X = 1, Y = 1 }, cts.Token); await utils.ReceiveFromSocketAsync <MoveResultMessage>(firstPlayerSocket); await utils.ReceiveFromSocketAsync <MoveResultMessage>(secondPlayerSocket); // X|O| // O|X|X // O|x|O await utils.SendThroughSocketAsync(secondPlayerSocket, new MakeMoveMessage() { X = 0, Y = 2 }, cts.Token); var msg1 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( firstPlayerSocket); var msg2 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( secondPlayerSocket); Assert.AreEqual(PlayResult.Draw.ToString(), msg1.Message); Assert.AreEqual(PlayResult.Draw.ToString(), msg2.Message); var status = WebSocketCloseStatus.NormalClosure; await clientSocket1.CloseAsync(status, "", cts.Token); await clientSocket2.CloseAsync(status, "", cts.Token); }
private async Task RunSvcAsync() { string errorMsg = ""; string updateMsg = ""; using (cancellationTokenSourceManual = new CancellationTokenSource()) { ClientWebSocket stream = null; try { DeviceStreamRequest deviceStreamRequest = new DeviceStreamRequest( streamName: "TestStream" ); updateMsg = "Starting Svc TestStream"; UpdateStatus(updateMsg); cancellationTokenSourceManual.Token.Register(() => { _serviceClient?.CloseAsync(); _serviceClient?.Dispose(); }); DeviceStreamResponse result = await _serviceClient.CreateStreamAsync(_deviceId, deviceStreamRequest).ConfigureAwait(false); updateMsg = string.Format("Svc Stream response received: Name={0} IsAccepted={1}", deviceStreamRequest.StreamName, result.IsAccepted); UpdateStatus(updateMsg); if (result.IsAccepted) { using (cancellationTokenSourceTimeout = new CancellationTokenSource(DeviceStreamingCommon.DeviceTimeout)) { try { using (stream = await DeviceStreamingCommon.GetStreamingClientAsync(result.Url, result.AuthorizationToken, cancellationTokenSourceTimeout.Token).ConfigureAwait(false)) { updateMsg = "Stream is open."; UpdateStatus(updateMsg); bool keepAlive = false; MsgOutWaitHandle = new AutoResetEvent(true); do { //Nb: Not waited on first entry as waiting for msgOut, which we already have. updateMsg = "Stream is open. Waiting for msg to send."; UpdateStatus(updateMsg); MsgOutWaitHandle.WaitOne(); updateMsg = "Sending msg."; UpdateStatus(updateMsg); bool caught = false; try { MsgOut = SvcCurrentSettings.ProcessMsgOut(MsgOut, SvcCurrentSettings.KeepAlive, SvcCurrentSettings.ResponseExpected, DevKeepListening , DevAutoStart ); } catch (NotImplementedException ) { errorMsg += "DeviceCurrentSettings not properly implemented"; keepAlive = false; caught = true; } if (!caught) { await SendMsg(stream, MsgOut, cancellationTokenSourceTimeout); updateMsg = "Sent msg."; UpdateStatus(updateMsg); if (this.SvcCurrentSettings.ResponseExpected) { byte[] receiveBuffer = new byte[1024]; System.ArraySegment<byte> ReceiveBuffer = new ArraySegment<byte>(receiveBuffer); var receiveResult = await stream.ReceiveAsync(ReceiveBuffer, cancellationTokenSourceTimeout.Token).ConfigureAwait(false); MsgIn = Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count); string subStrn = Azure_IoTHub_DeviceStreaming.DeviceStreamingCommon.DeviceInSimuatedDeviceModeStrn; int subStrnLen = subStrn.Length; string subStrn2 = Azure_IoTHub_Sensors.TelemetryDataPoint.Prefix; int subStrnLen2 = subStrn2.Length; if (MsgIn.Length>= subStrnLen) if (MsgIn.Substring(0,subStrnLen) == subStrn) { MsgIn = MsgIn.Substring(subStrnLen); Azure_IoTHub_Telemetry.SyntheticIoTMessage iotHubMessage = Azure_IoTHub_Telemetry.SyntheticIoTMessage.Deserialize(MsgIn); Microsoft.Azure.Devices.Client.Message message = iotHubMessage.ToMessage(); Microsoft.Azure.EventHubs.EventData eventData = Azure_IoTHub_Telemetry.SyntheticIoTMessage.ToEventData(message); MsgIn = Azure_IoTHub_Telemetry.SyntheticIoTMessage.EventData_ToString(eventData); } else if (MsgIn.Length >= subStrnLen2) if (MsgIn.Substring(0, subStrnLen2) == subStrn2) { MsgIn = MsgIn.Substring(subStrnLen2); Azure_IoTHub_Sensors.TelemetryDataPoint telemetry = Azure_IoTHub_Sensors.TelemetryDataPoint.Deserialize(MsgIn); MsgIn = telemetry.ToString(); //Microsoft.Azure.Devices.Client.Message message = iotHubMessage.ToMessage(); //Microsoft.Azure.EventHubs.EventData eventData = Azure_IoTHub_Telemetry.SyntheticIoTMessage.ToEventData(message); //MsgIn = Azure_IoTHub_Telemetry.SyntheticIoTMessage.EventData_ToString(eventData); } keepAlive = false; if (SvcCurrentSettings != null) keepAlive = this.SvcCurrentSettings.KeepAlive; try { if (OnRecvdTextD != null) OnRecvdTextD(MsgIn); } catch (Exception exx) { errorMsg += "OnRecvdTextD not properly implemented: " + exx.Message; keepAlive = false; } updateMsg = string.Format("Svc Received stream data: {0}", MsgIn); UpdateStatus(updateMsg); } MsgOutWaitHandle.Reset(); } } while (keepAlive) ; MsgOutWaitHandle = null; updateMsg = "Closing Svc Socket"; UpdateStatus(updateMsg); await stream.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationTokenSourceTimeout.Token).ConfigureAwait(false); stream = null; } } catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Hub connection failure"); errorMsg = "Hub connection failure"; } catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Device not found"); errorMsg = "Device not found"; } catch (TaskCanceledException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Task cancelled"); errorMsg = "Task cancelled"; } catch (OperationCanceledException) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Operation cancelled"); errorMsg = "Operation cancelled"; } catch (Exception ex) { if ((bool)cancellationTokenSourceManual?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Cancelled."); errorMsg = "Cancelled"; } else if ((bool)cancellationTokenSourceTimeout?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): Timed Out."); errorMsg = "Timed Out"; } else if (!ex.Message.Contains("Timed out")) { System.Diagnostics.Debug.WriteLine("1 Error RunSvcAsync(): " + ex.Message); errorMsg = ex.Message; } else { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed out"); errorMsg = "Timed Out"; } } } } } catch (Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Hub connection failure"); errorMsg += " Hub connection failure"; } catch (Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Device not found"); errorMsg += " Device not found"; } catch (TaskCanceledException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Task cancelled"); errorMsg += " Task cancelled"; } catch (OperationCanceledException) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Operation cancelled"); errorMsg += " Operation cancelled"; } catch (Exception ex) { if ((bool)cancellationTokenSourceManual?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Cancelled."); errorMsg += " Cancelled"; } else if ((bool)cancellationTokenSourceTimeout?.IsCancellationRequested) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed Out."); errorMsg += " Timed Out"; } else if (!ex.Message.Contains("Timed out")) { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): " + ex.Message); errorMsg += " " + ex.Message; } else { System.Diagnostics.Debug.WriteLine("2 Error RunSvcAsync(): Timed out"); errorMsg += " Timed Out"; } }; if (stream != null) { if (stream.CloseStatus != WebSocketCloseStatus.NormalClosure) { updateMsg= "Aborting Svc Socket as is errant or cancelled: " + errorMsg; UpdateStatus(updateMsg); stream.Abort(); updateMsg = "Aborted Svc Socket as was errant or cancelled:" + errorMsg; UpdateStatus(updateMsg); } else { updateMsg = "Socket closed normally: " + errorMsg; UpdateStatus(updateMsg); } stream = null; } else { updateMsg = "Socket closed Normally: " + errorMsg; UpdateStatus(updateMsg); } deviceStream_Svc = null; MsgOutWaitHandle = null; cancellationTokenSourceTimeout = null; } }
/// <summary>Send a json encoded text message</summary> public static async Task SendAsync(this ClientWebSocket ws, string json, CancellationToken cancel) { Trace.WriteLine($"Send: {json}"); var data = new ArraySegment <byte>(Encoding.UTF8.GetBytes(json)); await ws.SendAsync(data, WebSocketMessageType.Text, true, cancel); }
private async Task <BlittableJsonReaderObject> Receive(ClientWebSocket webSocket, JsonOperationContext context) { BlittableJsonDocumentBuilder builder = null; try { if (webSocket.State != WebSocketState.Open) { throw new InvalidOperationException( $"Trying to 'ReceiveAsync' WebSocket while not in Open state. State is {webSocket.State}"); } var state = new JsonParserState(); JsonOperationContext.ManagedPinnedBuffer buffer; using (context.GetManagedBuffer(out buffer)) using (var parser = new UnmanagedJsonParser(context, state, "")) //TODO: FIXME { builder = new BlittableJsonDocumentBuilder(context, BlittableJsonDocumentBuilder.UsageMode.None, nameof(TrafficRec) + "." + nameof(Receive), parser, state); builder.ReadObjectDocument(); while (builder.Read() == false) { var result = await webSocket.ReceiveAsync(buffer.Buffer, CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { if (_logger.IsInfoEnabled) { _logger.Info("Client got close message from server and is closing connection"); } builder.Dispose(); // actual socket close from dispose return(null); } if (result.EndOfMessage == false) { throw new EndOfStreamException("Stream ended without reaching end of json content."); } parser.SetBuffer(buffer, 0, result.Count); } builder.FinalizeDocument(); return(builder.CreateReader()); } } catch (WebSocketException ex) { builder?.Dispose(); if (_logger.IsInfoEnabled) { _logger.Info("Failed to receive a message, client was probably disconnected", ex); } throw; } }
public HttpListenerContextTests() { Factory = new HttpListenerFactory(); Socket = new ClientWebSocket(); }
/// <summary> /// Initializes a new instance of the <see cref="T:Kraken.WebSockets.KrakenWebsocket"/> class. /// </summary> /// <param name="uri">URI.</param> public KrakenWebSocket(string uri, IKrakenMessageSerializer serializer) { this.uri = uri ?? throw new ArgumentNullException(nameof(uri)); this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); webSocket = new ClientWebSocket(); }
void SetupClientWebSocket(ClientWebSocket clientWebSocket) { if (_options.ProxyOptions != null) { clientWebSocket.Options.Proxy = CreateProxy(); } if (_options.RequestHeaders != null) { foreach (var requestHeader in _options.RequestHeaders) { clientWebSocket.Options.SetRequestHeader(requestHeader.Key, requestHeader.Value); } } if (_options.SubProtocols != null) { foreach (var subProtocol in _options.SubProtocols) { clientWebSocket.Options.AddSubProtocol(subProtocol); } } if (_options.CookieContainer != null) { clientWebSocket.Options.Cookies = _options.CookieContainer; } if (_options.TlsOptions?.UseTls == true && _options.TlsOptions?.Certificates != null) { clientWebSocket.Options.ClientCertificates = new X509CertificateCollection(); foreach (var certificate in _options.TlsOptions.Certificates) { #if WINDOWS_UWP clientWebSocket.Options.ClientCertificates.Add(new X509Certificate(certificate)); #else clientWebSocket.Options.ClientCertificates.Add(certificate); #endif } } var certificateValidationHandler = _options.TlsOptions?.CertificateValidationHandler; #if NETSTANDARD2_1 if (certificateValidationHandler != null) { clientWebSocket.Options.RemoteCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => { // TODO: Find a way to add client options to same callback. Problem is that they have a different type. var context = new MqttClientCertificateValidationCallbackContext { Certificate = certificate, Chain = chain, SslPolicyErrors = sslPolicyErrors, ClientOptions = _options }; return(certificateValidationHandler(context)); }); } #else if (certificateValidationHandler != null) { throw new NotSupportedException("The remote certificate validation callback for Web Sockets is only supported for netstandard 2.1+"); } #endif }
public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[2]; await SendAsync( cws, WebSocketData.GetBufferFromText(".delay5sec"), WebSocketMessageType.Text, true, cts.Token); var recvBuffer = new byte[100]; var recvSegment = new ArraySegment <byte>(recvBuffer); try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = ReceiveAsync(cws, recvSegment, cts.Token); } Task.WaitAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (AggregateException ag) { foreach (var ex in ag.InnerExceptions) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "ReceiveAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else if (ex is OperationCanceledException) { Assert.Equal(WebSocketState.Aborted, cws.State); } else { Assert.True(false, "Unexpected exception: " + ex.Message); } } } } }
public void Configure(string registryadress, string registryport) { registry = Register(registryadress, registryport).GetAwaiter().GetResult(); }
public async Task SendReceive_ConnectionClosedPrematurely_ReceiveAsyncFailsAndWebSocketStateUpdated() { var options = new LoopbackServer.Options { WebSocketEndpoint = true }; Func <ClientWebSocket, Socket, Uri, Task> connectToServerThatAbortsConnection = async(clientSocket, server, url) => { AutoResetEvent pendingReceiveAsyncPosted = new AutoResetEvent(false); // Start listening for incoming connections on the server side. Task <List <string> > acceptTask = LoopbackServer.AcceptSocketAsync(server, async(socket, stream, reader, writer) => { // Complete the WebSocket upgrade. After this is done, the client-side ConnectAsync should complete. Assert.True(await LoopbackServer.WebSocketHandshakeAsync(socket, reader, writer)); // Wait for client-side ConnectAsync to complete and for a pending ReceiveAsync to be posted. pendingReceiveAsyncPosted.WaitOne(TimeOutMilliseconds); // Close the underlying connection prematurely (without sending a WebSocket Close frame). socket.Shutdown(SocketShutdown.Both); socket.Close(); return(null); }, options); // Initiate a connection attempt. var cts = new CancellationTokenSource(TimeOutMilliseconds); await clientSocket.ConnectAsync(url, cts.Token); // Post a pending ReceiveAsync before the TCP connection is torn down. var recvBuffer = new byte[100]; var recvSegment = new ArraySegment <byte>(recvBuffer); Task pendingReceiveAsync = ReceiveAsync(clientSocket, recvSegment, cts.Token); pendingReceiveAsyncPosted.Set(); // Wait for the server to close the underlying connection. acceptTask.Wait(cts.Token); // Validate I/O errors and socket state. if (PlatformDetection.IsFullFramework) { _output.WriteLine("[Windows] ManagedWebSocket-based implementation."); WebSocketException pendingReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); WebSocketException newReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token)); Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode); Assert.Equal( ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"), newReceiveException.Message); Assert.Equal(WebSocketState.Aborted, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } else if (PlatformDetection.IsUap) { _output.WriteLine("WinRTWebSocket-based implementation."); const uint WININET_E_CONNECTION_ABORTED = 0x80072EFE; WebSocketException pendingReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); Assert.NotNull(pendingReceiveException.InnerException); Assert.Equal(WININET_E_CONNECTION_ABORTED, (uint)pendingReceiveException.InnerException.HResult); WebSocketException newReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token)); Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode); Assert.Equal( ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"), newReceiveException.Message); Assert.Equal(WebSocketState.Aborted, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } else { _output.WriteLine("[Non-Windows] ManagedWebSocket-based implementation."); WebSocketException pendingReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); WebSocketException newReceiveException = await Assert.ThrowsAsync <WebSocketException>(() => ReceiveAsync(clientSocket, recvSegment, cts.Token)); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, newReceiveException.WebSocketErrorCode); Assert.Equal(WebSocketState.Open, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } }; await LoopbackServer.CreateServerAsync(async (server, url) => { using (ClientWebSocket clientSocket = new ClientWebSocket()) { await connectToServerThatAbortsConnection(clientSocket, server, url); } }, options); }
public void Ctor_ExpectedPropertyValues() { using (var cws = new ClientWebSocket()) { Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.None, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); } }
static async Task WebsocketSend(ClientWebSocket cws, string id, string details) { string jsonData = JsonConvert.SerializeObject(new { id = $"{id}", type = "start", payload = new{ query = details } }); ArraySegment <byte> b = new ArraySegment <byte>(Encoding.ASCII.GetBytes(jsonData)); await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None); }
public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); }
//Call GetWsReturn to wait for a message from a websocket. GetWsReturn has to be called for each message static async void GetWsReturn(ClientWebSocket cws) { ArraySegment <byte> buf = new ArraySegment <byte>(new byte[1024]); buf = WebSocket.CreateClientBuffer(1024, 1024); WebSocketReceiveResult r; string result = ""; do { r = await cws.ReceiveAsync(buf, CancellationToken.None); result += Encoding.UTF8.GetString(buf.Array ?? throw new ApplicationException("Buf = null"), buf.Offset, r.Count); } while (!r.EndOfMessage); if (String.IsNullOrEmpty(result)) { return; } JObject obj = new JObject(); try{ obj = JObject.Parse(result); } catch (JsonReaderException e) { throw new ApplicationException(e.Message); } string subType = (string)obj["type"]; switch (subType) { case "connection_ack": { Debug.Log("init_success, the handshake is complete"); OnSubscriptionHandshakeComplete subscriptionHandshakeComplete = new OnSubscriptionHandshakeComplete(); subscriptionHandshakeComplete.FireEvent(); GetWsReturn(cws); break; } case "error": { throw new ApplicationException("The handshake failed. Error: " + result); } case "connection_error": { throw new ApplicationException("The handshake failed. Error: " + result); } case "data": { OnSubscriptionDataReceived subscriptionDataReceived = new OnSubscriptionDataReceived(result); subscriptionDataReceived.FireEvent(); GetWsReturn(cws); break; } case "ka": { GetWsReturn(cws); break; } case "subscription_fail": { throw new ApplicationException("The subscription data failed"); } } }
public void Configure(string registryadress, string registryport, string agentaddress, int agentport, int reporterport) { reporter = new Reporter(agentaddress, agentport, reporterport, this); registry = Register(registryadress, registryport).GetAwaiter().GetResult(); }
public async Task MakingCorrectMoveReturnsMoveResultMessageWithSuccessMessage() { var cts = new CancellationTokenSource(); var clientSocket1 = new ClientWebSocket(); var clientSocket2 = new ClientWebSocket(); await clientSocket1.ConnectAsync(utils.serverUrl, cts.Token); await clientSocket2.ConnectAsync(utils.serverUrl, cts.Token); var findMsg = new FindGameMessage() { Size = 3 }; await utils.SendThroughSocketAsync(clientSocket1, findMsg, cts.Token); await utils.SendThroughSocketAsync(clientSocket2, findMsg, cts.Token); var gameFoundMsg1 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket1); var gameFoundMsg2 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket2); ClientWebSocket firstPlayerSocket, secondPlayerSocket; if (gameFoundMsg1.IsClientTurn) { firstPlayerSocket = clientSocket1; secondPlayerSocket = clientSocket2; } else { firstPlayerSocket = clientSocket2; secondPlayerSocket = clientSocket1; } int x = 1; int y = 2; await utils.SendThroughSocketAsync(firstPlayerSocket, new MakeMoveMessage() { X = x, Y = y }, cts.Token); var moveResultMessage1 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( firstPlayerSocket); var moveResultMessage2 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( secondPlayerSocket); Assert.AreEqual(PlayResult.Success.ToString(), moveResultMessage1.Message); Assert.AreEqual(PlayResult.Success.ToString(), moveResultMessage2.Message); Assert.AreEqual(x, moveResultMessage1.X); Assert.AreEqual(x, moveResultMessage2.X); Assert.AreEqual(y, moveResultMessage1.Y); Assert.AreEqual(y, moveResultMessage2.Y); var status = WebSocketCloseStatus.NormalClosure; await clientSocket1.CloseAsync(status, "", cts.Token); await clientSocket2.CloseAsync(status, "", cts.Token); }
public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server) { const string AcceptedProtocol = "CustomProtocol"; using (var cws = new ClientWebSocket()) { var cts = new CancellationTokenSource(TimeOutMilliseconds); var ub = new UriBuilder(server); ub.Query = "subprotocol=" + AcceptedProtocol; WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token)); Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message); } }
public async Task TestMultipleSessions() { var cts = new CancellationTokenSource(); var clientSocket1 = new ClientWebSocket(); var clientSocket2 = new ClientWebSocket(); var clientSocket3 = new ClientWebSocket(); var clientSocket4 = new ClientWebSocket(); await clientSocket1.ConnectAsync(utils.serverUrl, cts.Token); await clientSocket2.ConnectAsync(utils.serverUrl, cts.Token); await clientSocket3.ConnectAsync(utils.serverUrl, cts.Token); await clientSocket4.ConnectAsync(utils.serverUrl, cts.Token); var findMsg = new FindGameMessage() { Size = 3 }; await utils.SendThroughSocketAsync(clientSocket1, findMsg, cts.Token); await utils.SendThroughSocketAsync(clientSocket2, findMsg, cts.Token); await utils.SendThroughSocketAsync(clientSocket3, findMsg, cts.Token); await utils.SendThroughSocketAsync(clientSocket4, findMsg, cts.Token); var gameFoundMsg1 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket1); var gameFoundMsg2 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket2); var gameFoundMsg3 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket3); var gameFoundMsg4 = await utils.ReceiveFromSocketAsync <GameFoundMessage>( clientSocket4); Assert.AreNotEqual(gameFoundMsg1.IsClientTurn, gameFoundMsg2.IsClientTurn); Assert.AreNotEqual(gameFoundMsg3.IsClientTurn, gameFoundMsg4.IsClientTurn); ClientWebSocket firstPlayerSocketOfFirstSession; ClientWebSocket secondPlayerSocketOfFirstSession; if (gameFoundMsg1.IsClientTurn) { firstPlayerSocketOfFirstSession = clientSocket1; secondPlayerSocketOfFirstSession = clientSocket2; } else { firstPlayerSocketOfFirstSession = clientSocket2; secondPlayerSocketOfFirstSession = clientSocket1; } ClientWebSocket firstPlayerSocketOfSecondSession; ClientWebSocket secondPlayerSocketOfSecondSession; if (gameFoundMsg3.IsClientTurn) { firstPlayerSocketOfSecondSession = clientSocket3; secondPlayerSocketOfSecondSession = clientSocket4; } else { firstPlayerSocketOfSecondSession = clientSocket4; secondPlayerSocketOfSecondSession = clientSocket3; } await utils.SendThroughSocketAsync(firstPlayerSocketOfSecondSession, new MakeMoveMessage() { X = 2, Y = 2 }, cts.Token); var moveResultMsg1 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( firstPlayerSocketOfSecondSession); var moveResultMsg2 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( secondPlayerSocketOfSecondSession); Assert.AreEqual(moveResultMsg1.X, 2); Assert.AreEqual(moveResultMsg1.Y, 2); Assert.AreEqual(moveResultMsg2.X, 2); Assert.AreEqual(moveResultMsg2.Y, 2); await utils.SendThroughSocketAsync(firstPlayerSocketOfFirstSession, new MakeMoveMessage() { X = 1, Y = 1 }, cts.Token); var moveResultMsg3 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( firstPlayerSocketOfFirstSession); var moveResultMsg4 = await utils.ReceiveFromSocketAsync <MoveResultMessage>( secondPlayerSocketOfFirstSession); Assert.AreEqual(moveResultMsg3.X, 1); Assert.AreEqual(moveResultMsg3.Y, 1); Assert.AreEqual(moveResultMsg4.X, 1); Assert.AreEqual(moveResultMsg4.Y, 1); var status = WebSocketCloseStatus.NormalClosure; await clientSocket1.CloseAsync(status, "", cts.Token); await clientSocket2.CloseAsync(status, "", cts.Token); await clientSocket3.CloseAsync(status, "", cts.Token); await clientSocket4.CloseAsync(status, "", cts.Token); }
/// <summary> /// Attempts a send to a remote web socket server. If there is an existing connection it will be used /// otherwise an attempt will made to establish a new one. /// </summary> /// <param name="serverEndPoint">The remote web socket server URI to send to.</param> /// <param name="buffer">The data buffer to send.</param> /// <returns>A success value or an error for failure.</returns> private async Task <SocketError> SendAsync(SIPEndPoint serverEndPoint, byte[] buffer) { try { string uriPrefix = (serverEndPoint.Protocol == SIPProtocolsEnum.wss) ? WEB_SOCKET_SECURE_URI_PREFIX : WEB_SOCKET_URI_PREFIX; var serverUri = new Uri($"{uriPrefix}{serverEndPoint.GetIPEndPoint()}"); string connectionID = GetConnectionID(serverUri); serverEndPoint.ChannelID = this.ID; serverEndPoint.ConnectionID = connectionID; if (m_egressConnections.TryGetValue(connectionID, out var conn)) { logger.LogDebug($"Sending {buffer.Length} bytes on client web socket connection to {conn.ServerUri}."); ArraySegment <byte> segmentBuffer = new ArraySegment <byte>(buffer); await conn.Client.SendAsync(segmentBuffer, WebSocketMessageType.Text, true, m_cts.Token).ConfigureAwait(false); return(SocketError.Success); } else { // Attempt a new connection. ClientWebSocket clientWebSocket = new ClientWebSocket(); await clientWebSocket.ConnectAsync(serverUri, m_cts.Token).ConfigureAwait(false); logger.LogDebug($"Successfully connected web socket client to {serverUri}."); ArraySegment <byte> segmentBuffer = new ArraySegment <byte>(buffer); await clientWebSocket.SendAsync(segmentBuffer, WebSocketMessageType.Text, true, m_cts.Token).ConfigureAwait(false); var recvBuffer = new ArraySegment <byte>(new byte[2 * SIPStreamConnection.MaxSIPTCPMessageSize]); Task <WebSocketReceiveResult> receiveTask = clientWebSocket.ReceiveAsync(recvBuffer, m_cts.Token); // There's currently no way to get the socket IP end point used by the client web socket to establish // the connection. Instead provide a dummy local end point that has as much of the information as we can. IPEndPoint localEndPoint = new IPEndPoint((serverEndPoint.Address.AddressFamily == AddressFamily.InterNetwork) ? IPAddress.Any : IPAddress.IPv6Any, 0); SIPEndPoint localSIPEndPoint = new SIPEndPoint(serverEndPoint.Protocol, localEndPoint, this.ID, connectionID); ClientWebSocketConnection newConn = new ClientWebSocketConnection { LocalEndPoint = localSIPEndPoint, ServerUri = serverUri, RemoteEndPoint = serverEndPoint, ConnectionID = connectionID, ReceiveBuffer = recvBuffer, ReceiveTask = receiveTask, Client = clientWebSocket }; if (!m_egressConnections.TryAdd(connectionID, newConn)) { logger.LogError($"Could not add web socket client connected to {serverUri} to channel collection, closing."); await Close(connectionID, clientWebSocket).ConfigureAwait(false); } else { if (!m_isReceiveTaskRunning) { m_isReceiveTaskRunning = true; _ = Task.Factory.StartNew(MonitorReceiveTasks, TaskCreationOptions.LongRunning); } } return(SocketError.Success); } } catch (SocketException sockExcp) { return(sockExcp.SocketErrorCode); } }
public static void TestBinanceTickers() { const int BYTE_SIZE = 1024; Console.WriteLine("LAUNCH: Binance"); var socket = new ClientWebSocket(); Task task = socket.ConnectAsync(new Uri("wss://stream.binance.com:9443/stream?streams=btcusdt@trade/ethusdt@trade/ethbtc@trade"), CancellationToken.None); task.Wait(); Thread readThread = new Thread( delegate(object obj) { byte[] recBytes = new byte[BYTE_SIZE]; while (true) { ArraySegment <byte> t = new ArraySegment <byte>(recBytes); Task <WebSocketReceiveResult> receiveAsync = socket.ReceiveAsync(t, CancellationToken.None); receiveAsync.Wait(); string jsonString = Encoding.UTF8.GetString(recBytes); //Console.WriteLine("jsonString = {0}", jsonString); JObject jo = JsonConvert.DeserializeObject <JObject>(jsonString); string stream = jo["stream"].Value <string>(); jo = jo["data"].Value <JObject>(); string type = jo["e"].Value <string>(); //Console.WriteLine("stream: {0} eventType: {1}", stream, type); if (type == "trade") // "trade": { //string pid = jo["product_id"].Value<string>(); int i = stream.IndexOf("@"); string pid = stream.Substring(0, i); string price = jo["p"].Value <string>(); long time = jo["E"].Value <long>(); string size = jo["q"].Value <string>(); Console.WriteLine("{0} {1} {2} {3}", pid, price, size, time); } /*else if (type == "update") // "update" * { * //Console.WriteLine(jsonString); * } * else if (type == "error") // "error" * { * } * else if (type == "heartbeat") // "heartbeat" * { * }*/ Array.Clear(recBytes, 0, BYTE_SIZE); //recBytes = new byte[BYTE_SIZE]; } }); readThread.Start(); //Console.ReadLine(); }
public void Abort_CreateAndAbort_StateIsClosed() { var cws = new ClientWebSocket(); cws.Abort(); Assert.Equal(WebSocketState.Closed, cws.State); }