private static async Task OnServerTextReceived(AsyncWebSocketClient client, string text) { Console.Write(string.Format("WebSocket server [{0}] received Text --> ", client.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await Task.CompletedTask; }
static void Main(string[] args) { NLogLogger.Use(); Task.Run(async() => { try { var config = new AsyncWebSocketClientConfiguration(); //config.SslTargetHost = "Cowboy"; //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer")); //config.SslPolicyErrorsBypassed = true; //var uri = new Uri("ws://echo.websocket.org/"); //var uri = new Uri("wss://127.0.0.1:22222/test"); var uri = new Uri("ws://127.0.0.1:22222/test"); _client = new AsyncWebSocketClient(uri, OnServerTextReceived, OnServerBinaryReceived, OnServerConnected, OnServerDisconnected, config); await _client.Connect(); Console.WriteLine("WebSocket client has connected to server [{0}].", uri); Console.WriteLine("Type something to send to server..."); while (_client.State == WebSocketState.Open) { try { string text = Console.ReadLine(); if (text == "quit") { break; } Task.Run(async() => { //await _client.SendText(text); //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); }).Forget(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } await _client.Close(WebSocketCloseCode.NormalClosure); Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri); } catch (Exception ex) { Logger.Get <Program>().Error(ex.Message, ex); } }).Wait(); Console.ReadKey(); }
public async Task OnServerFragmentationStreamContinued(AsyncWebSocketClient client, byte[] data, int offset, int count) { if (_onServerFragmentationStreamContinued != null) { await _onServerFragmentationStreamContinued(client, data, offset, count); } }
private static async Task OnServerTextReceived(AsyncWebSocketClient client, string text) { Console.Write(string.Format("WebSocket server [{0}] received Text --> ", client.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await Task.CompletedTask; }
public async Task OnServerDisconnected(AsyncWebSocketClient client) { if (_onServerDisconnected != null) { await _onServerDisconnected(client); } }
public async Task OnServerBinaryReceived(AsyncWebSocketClient client, byte[] data, int offset, int count) { if (_onServerBinaryReceived != null) { await _onServerBinaryReceived(client, data, offset, count); } }
public async Task OnServerTextReceived(AsyncWebSocketClient client, string text) { if (_onServerTextReceived != null) { await _onServerTextReceived(client, text); } }
private static async Task OnServerBinaryReceived(AsyncWebSocketClient client, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); Console.Write(string.Format("WebSocket server [{0}] received Binary --> ", client.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await Task.CompletedTask; }
static void Main(string[] args) { NLogLogger.Use(); Task.Run(async () => { try { var config = new AsyncWebSocketClientConfiguration(); //config.SslTargetHost = "Cowboy"; //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer")); //config.SslPolicyErrorsBypassed = true; //var uri = new Uri("ws://echo.websocket.org/"); //var uri = new Uri("wss://127.0.0.1:22222/test"); var uri = new Uri("ws://127.0.0.1:22222/test"); _client = new AsyncWebSocketClient(uri, OnServerTextReceived, OnServerBinaryReceived, OnServerConnected, OnServerDisconnected, config); await _client.Connect(); Console.WriteLine("WebSocket client has connected to server [{0}].", uri); Console.WriteLine("Type something to send to server..."); while (_client.State == WebSocketState.Open) { try { string text = Console.ReadLine(); if (text == "quit") break; Task.Run(async () => { //await _client.SendText(text); //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); }).Forget(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } await _client.Close(WebSocketCloseCode.NormalClosure); Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri); } catch (Exception ex) { Logger.Get<Program>().Error(ex.Message, ex); } }).Wait(); Console.ReadKey(); }
private static async Task OnServerBinaryReceived(AsyncWebSocketClient client, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); Console.Write(string.Format("WebSocket server [{0}] received Binary --> ", client.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await Task.CompletedTask; }
private async Task PerformWebSocketLoad(int connections, IPEndPoint remoteEP) { var channels = new List <AsyncWebSocketClient>(); var configuration = new AsyncWebSocketClientConfiguration(); configuration.SslPolicyErrorsBypassed = _options.IsSetSslPolicyErrorsBypassed; configuration.SslTargetHost = _options.SslTargetHost; configuration.SslClientCertificates = _options.SslClientCertificates; string uriString = string.Format("{0}://{1}/{2}", _options.IsSetSsl ? "wss" : "ws", remoteEP, _options.IsSetWebSocketPath ? _options.WebSocketPath.TrimStart('/') : ""); var uri = new Uri(uriString); for (int c = 0; c < connections; c++) { var client = new AsyncWebSocketClient(uri, onServerTextReceived: async(s, b) => { await Task.CompletedTask; }, onServerBinaryReceived: async(s, b, o, l) => { await Task.CompletedTask; }, onServerConnected: async(s) => { await Task.CompletedTask; }, onServerDisconnected: async(s) => { await Task.CompletedTask; }, configuration: configuration); try { _logger(string.Format("Connecting to [{0}].", remoteEP)); await client.Connect(); channels.Add(client); _logger(string.Format("Connected to [{0}] from [{1}].", remoteEP, client.LocalEndPoint)); } catch (Exception ex) when(!ShouldThrow(ex)) { if (ex is AggregateException) { var a = ex as AggregateException; if (a.InnerExceptions != null && a.InnerExceptions.Any()) { _logger(string.Format("Connect to [{0}] error occurred [{1}].", remoteEP, a.InnerExceptions.First().Message)); } } else { _logger(string.Format("Connect to [{0}] error occurred [{1}].", remoteEP, ex.Message)); } if (client != null) { await client.Close(WebSocketCloseCode.AbnormalClosure); } } } if (_options.IsSetChannelLifetime && channels.Any()) { await Task.Delay(_options.ChannelLifetime); } foreach (var client in channels) { try { _logger(string.Format("Closed to [{0}] from [{1}].", remoteEP, client.LocalEndPoint)); await client.Close(WebSocketCloseCode.NormalClosure); } catch (Exception ex) when(!ShouldThrow(ex)) { if (ex is AggregateException) { var a = ex as AggregateException; if (a.InnerExceptions != null && a.InnerExceptions.Any()) { _logger(string.Format("Closed to [{0}] error occurred [{1}].", remoteEP, a.InnerExceptions.First().Message)); } } else { _logger(string.Format("Closed to [{0}] error occurred [{1}].", remoteEP, ex.Message)); } } } }
internal static byte[] CreateOpenningHandshakeRequest(AsyncWebSocketClient client, out string secWebSocketKey) { var sb = new StringBuilder(); // The handshake MUST be a valid HTTP request as specified by [RFC2616]. // The method of the request MUST be GET, and the HTTP version MUST be at least 1.1. // For example, if the WebSocket URI is "ws://example.com/chat", // the first line sent should be "GET /chat HTTP/1.1". sb.AppendFormatWithCrCf("GET {0} HTTP/{1}", !string.IsNullOrEmpty(client.Uri.PathAndQuery) ? client.Uri.PathAndQuery : "/", Consts.HttpVersion); // The request MUST contain a |Host| header field whose value // contains /host/ plus optionally ":" followed by /port/ (when not // using the default port). sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Host, client.Uri.Host); // The request MUST contain an |Upgrade| header field whose value // MUST include the "websocket" keyword. sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Upgrade, Consts.WebSocketUpgradeToken); // The request MUST contain a |Connection| header field whose value // MUST include the "Upgrade" token. sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.Connection, Consts.WebSocketConnectionToken); // The request MUST include a header field with the name // |Sec-WebSocket-Key|. The value of this header field MUST be a // nonce consisting of a randomly selected 16-byte value that has // been base64-encoded (see Section 4 of [RFC4648]). The nonce // MUST be selected randomly for each connection. secWebSocketKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Substring(0, 16))); sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketKey, secWebSocketKey); // The request MUST include a header field with the name // |Sec-WebSocket-Version|. The value of this header field MUST be 13. sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketVersion, Consts.WebSocketVersion); // The request MAY include a header field with the name // |Sec-WebSocket-Extensions|. If present, this value indicates // the protocol-level extension(s) the client wishes to speak. The // interpretation and format of this header field is described in Section 9.1. if (client.OfferedExtensions != null && client.OfferedExtensions.Any()) { foreach (var extension in client.OfferedExtensions) { sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketExtensions, extension.ExtensionNegotiationOffer); } } // The request MAY include a header field with the name // |Sec-WebSocket-Protocol|. If present, this value indicates one // or more comma-separated subprotocol the client wishes to speak, // ordered by preference. The elements that comprise this value // MUST be non-empty strings with characters in the range U+0021 to // U+007E not including separator characters as defined in // [RFC2616] and MUST all be unique strings. The ABNF for the // value of this header field is 1#token, where the definitions of // constructs and rules are as given in [RFC2616]. if (client.RequestedSubProtocols != null && client.RequestedSubProtocols.Any()) { foreach (var description in client.RequestedSubProtocols) { sb.AppendFormatWithCrCf(Consts.HttpHeaderLineFormat, HttpKnownHeaderNames.SecWebSocketProtocol, description.RequestedSubProtocol); } } // The request MUST include a header field with the name |Origin| // [RFC6454] if the request is coming from a browser client. If // the connection is from a non-browser client, the request MAY // include this header field if the semantics of that client match // the use-case described here for browser clients. The value of // this header field is the ASCII serialization of origin of the // context in which the code establishing the connection is // running. See [RFC6454] for the details of how this header field // value is constructed. // The request MAY include any other header fields, for example, // cookies [RFC6265] and/or authentication-related header fields // such as the |Authorization| header field [RFC2616], which are // processed according to documents that define them. sb.AppendWithCrCf(); // GET /chat HTTP/1.1 // Host: server.example.com // Upgrade: websocket // Connection: Upgrade // Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== // Sec-WebSocket-Protocol: chat, superchat // Sec-WebSocket-Version: 13 // Origin: http://example.com var request = sb.ToString(); #if DEBUG _log.DebugFormat("[{0}]{1}{2}", client.RemoteEndPoint, Environment.NewLine, request); #endif return(Encoding.UTF8.GetBytes(request)); }
internal static bool VerifyOpenningHandshakeResponse(AsyncWebSocketClient client, byte[] buffer, int offset, int count, string secWebSocketKey) { BufferValidator.ValidateBuffer(buffer, offset, count, "buffer"); if (string.IsNullOrEmpty(secWebSocketKey)) { throw new ArgumentNullException("secWebSocketKey"); } var response = Encoding.UTF8.GetString(buffer, offset, count); #if DEBUG _log.DebugFormat("[{0}]{1}{2}", client.RemoteEndPoint, Environment.NewLine, response); #endif try { // HTTP/1.1 101 Switching Protocols // Upgrade: websocket // Connection: Upgrade // Sec-WebSocket-Accept: 1tGBmA9p0DQDgmFll6P0/UcVS/E= // Sec-WebSocket-Protocol: chat Dictionary <string, string> headers; List <string> extensions; List <string> protocols; ParseOpenningHandshakeResponseHeaders(response, out headers, out extensions, out protocols); if (headers == null) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to invalid headers.", client.RemoteEndPoint)); } // If the status code received from the server is not 101, the // client handles the response per HTTP [RFC2616] procedures. In // particular, the client might perform authentication if it // receives a 401 status code; the server might redirect the client // using a 3xx status code (but clients are not required to follow them), etc. if (!headers.ContainsKey(Consts.HttpStatusCodeName)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to lack of status code.", client.RemoteEndPoint)); } if (!headers.ContainsKey(Consts.HttpStatusCodeDescription)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to lack of status description.", client.RemoteEndPoint)); } if (headers[Consts.HttpStatusCodeName] == ((int)HttpStatusCode.BadRequest).ToString()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to bad request [{1}].", client.RemoteEndPoint, headers[Consts.HttpStatusCodeName])); } if (headers[Consts.HttpStatusCodeName] != ((int)HttpStatusCode.SwitchingProtocols).ToString()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to expected 101 Switching Protocols but received [{1}].", client.RemoteEndPoint, headers[Consts.HttpStatusCodeName])); } // If the response lacks an |Upgrade| header field or the |Upgrade| // header field contains a value that is not an ASCII case- // insensitive match for the value "websocket", the client MUST // _Fail the WebSocket Connection_. if (!headers.ContainsKey(HttpKnownHeaderNames.Connection)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to lack of connection header item.", client.RemoteEndPoint)); } if (headers[HttpKnownHeaderNames.Connection].ToLowerInvariant() != Consts.WebSocketConnectionToken.ToLowerInvariant()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to invalid connection header item value [{1}].", client.RemoteEndPoint, headers[HttpKnownHeaderNames.Connection])); } // If the response lacks a |Connection| header field or the // |Connection| header field doesn't contain a token that is an // ASCII case-insensitive match for the value "Upgrade", the client // MUST _Fail the WebSocket Connection_. if (!headers.ContainsKey(HttpKnownHeaderNames.Upgrade)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to lack of upgrade header item.", client.RemoteEndPoint)); } if (headers[HttpKnownHeaderNames.Upgrade].ToLowerInvariant() != Consts.WebSocketUpgradeToken.ToLowerInvariant()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to invalid upgrade header item value [{1}].", client.RemoteEndPoint, headers[HttpKnownHeaderNames.Upgrade])); } // If the response lacks a |Sec-WebSocket-Accept| header field or // the |Sec-WebSocket-Accept| contains a value other than the // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- // Key| (as a string, not base64-decoded) with the string "258EAFA5- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and // trailing whitespace, the client MUST _Fail the WebSocket Connection_. if (!headers.ContainsKey(HttpKnownHeaderNames.SecWebSocketAccept)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to lack of Sec-WebSocket-Accept header item.", client.RemoteEndPoint)); } string challenge = GetSecWebSocketAcceptString(secWebSocketKey); if (!headers[HttpKnownHeaderNames.SecWebSocketAccept].Equals(challenge, StringComparison.OrdinalIgnoreCase)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to invalid Sec-WebSocket-Accept header item value [{1}].", client.RemoteEndPoint, headers[HttpKnownHeaderNames.SecWebSocketAccept])); } // If the response includes a |Sec-WebSocket-Extensions| header // field and this header field indicates the use of an extension // that was not present in the client's handshake (the server has // indicated an extension not requested by the client), the client // MUST _Fail the WebSocket Connection_. if (extensions != null) { foreach (var extension in extensions) { // The empty string is not the same as the null value for these // purposes and is not a legal value for this field. if (string.IsNullOrWhiteSpace(extension)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to empty extension.", client.RemoteEndPoint)); } } client.AgreeExtensions(extensions); } // If the response includes a |Sec-WebSocket-Protocol| header field // and this header field indicates the use of a subprotocol that was // not present in the client's handshake (the server has indicated a // subprotocol not requested by the client), the client MUST _Fail // the WebSocket Connection_. if (protocols != null) { if (!protocols.Any()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to empty sub-protocol.", client.RemoteEndPoint)); } if (protocols.Count > 1) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to suggest to use multiple sub-protocols.", client.RemoteEndPoint)); } foreach (var protocol in protocols) { // The empty string is not the same as the null value for these // purposes and is not a legal value for this field. if (string.IsNullOrWhiteSpace(protocol)) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to empty sub-protocol.", client.RemoteEndPoint)); } } var suggestedProtocols = protocols.First().Split(',') .Select(p => p.TrimStart().TrimEnd()).Where(p => !string.IsNullOrWhiteSpace(p)); if (!suggestedProtocols.Any()) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to invalid sub-protocol.", client.RemoteEndPoint)); } if (suggestedProtocols.Count() > 1) { throw new WebSocketHandshakeException(string.Format( "Handshake with remote [{0}] failed due to suggest to use multiple sub-protocols.", client.RemoteEndPoint)); } // The value chosen MUST be derived // from the client's handshake, specifically by selecting one of // the values from the |Sec-WebSocket-Protocol| field that the // server is willing to use for this connection (if any). client.UseSubProtocol(suggestedProtocols.First()); } } catch (Exception ex) { _log.ErrorFormat("{0}{1}{2}", client, Environment.NewLine, response); _log.Error(ex.Message, ex); throw; } return(true); }
static void Main(string[] args) { NLogLogger.Use(); Task.Run(async() => { try { var config = new AsyncWebSocketClientConfiguration(); //config.SslTargetHost = "Cowboy"; //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer")); //config.SslPolicyErrorsBypassed = true; //var uri = new Uri("ws://echo.websocket.org/"); //var uri = new Uri("wss://127.0.0.1:22222/test"); var uri = new Uri("ws://127.0.0.1:22222/test"); _client = new AsyncWebSocketClient(uri, OnServerTextReceived, OnServerBinaryReceived, OnServerConnected, OnServerDisconnected, config); await _client.Connect(); Console.WriteLine("WebSocket client has connected to server [{0}].", uri); Console.WriteLine("Type something to send to server..."); while (_client.State == WebSocketState.Open) { try { string text = Console.ReadLine(); if (text == "quit") { break; } Task.Run(async() => { if (text == "many") { text = new string('x', 1024); Stopwatch watch = Stopwatch.StartNew(); int count = 10000; for (int i = 1; i <= count; i++) { await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> Sequence[{1}] -> TextLength[{2}].", _client.LocalEndPoint, i, text.Length); } watch.Stop(); Console.WriteLine("Client [{0}] send binary -> Count[{1}] -> Cost[{2}] -> PerSecond[{3}].", _client.LocalEndPoint, count, watch.ElapsedMilliseconds / 1000, count / (watch.ElapsedMilliseconds / 1000)); } else if (text == "big") { text = new string('x', 1024 * 1024 * 100); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else { await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } //await _client.SendText(text); //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text); }).Forget(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } await _client.Close(WebSocketCloseCode.NormalClosure); Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri); } catch (Exception ex) { Logger.Get <Program>().Error(ex.Message, ex); } }).Wait(); Console.ReadKey(); }
static void Main(string[] args) { NLogLogger.Use(); Task.Run(async () => { try { var config = new AsyncWebSocketClientConfiguration(); //config.SslTargetHost = "Cowboy"; //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer")); //config.SslPolicyErrorsBypassed = true; //var uri = new Uri("ws://echo.websocket.org/"); //var uri = new Uri("wss://127.0.0.1:22222/test"); var uri = new Uri("ws://127.0.0.1:22222/test"); _client = new AsyncWebSocketClient(uri, OnServerTextReceived, OnServerBinaryReceived, OnServerConnected, OnServerDisconnected, config); await _client.Connect(); Console.WriteLine("WebSocket client has connected to server [{0}].", uri); Console.WriteLine("Type something to send to server..."); while (_client.State == WebSocketState.Open) { try { string text = Console.ReadLine(); if (text == "quit") break; Task.Run(async () => { if (text == "many") { text = new string('x', 1024); Stopwatch watch = Stopwatch.StartNew(); int count = 10000; for (int i = 1; i <= count; i++) { await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> Sequence[{1}] -> TextLength[{2}].", _client.LocalEndPoint, i, text.Length); } watch.Stop(); Console.WriteLine("Client [{0}] send binary -> Count[{1}] -> Cost[{2}] -> PerSecond[{3}].", _client.LocalEndPoint, count, watch.ElapsedMilliseconds / 1000, count / (watch.ElapsedMilliseconds / 1000)); } else if (text == "big") { text = new string('x', 1024 * 1024 * 100); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else if (text == "8192") { text = new string('x', 1024 * 8); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else if (text == "4096") { text = new string('x', 1024 * 4); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else if (text == "2048") { text = new string('x', 1024 * 2); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else if (text == "1024") { text = new string('x', 1024); await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else { await _client.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); //await _client.SendTextAsync(text); //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text); } }).Forget(); } catch (Exception ex) { Logger.Get<Program>().Error(ex.Message, ex); } } await _client.Close(WebSocketCloseCode.NormalClosure); Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri); } catch (Exception ex) { Logger.Get<Program>().Error(ex.Message, ex); } }).Wait(); Console.ReadKey(); }
private static async Task OnServerConnected(AsyncWebSocketClient client) { Console.WriteLine(string.Format("WebSocket server [{0}] has connected.", client.RemoteEndPoint)); await Task.CompletedTask; }
private static async Task OnServerDisconnected(AsyncWebSocketClient client) { Console.WriteLine(string.Format("WebSocket server [{0}] has disconnected.", client.RemoteEndPoint)); await Task.CompletedTask; }
public async Task <string> Put(string host, string id, string flag, int vuln) { var len = vuln == 1 ? RndUtil.Choice(11, 14) : RndUtil.Choice(12, 15); var name = RndText.RandomWord(len).RandomLeet().RandomUpperCase(); var b64Name = Convert.ToBase64String(Encoding.ASCII.GetBytes(name)); var b64Entropy = Convert.ToBase64String(Encoding.ASCII.GetBytes(flag)); await Console.Error.WriteLineAsync($"name '{name}', b64name '{b64Name}', entropy '{b64Entropy}'").ConfigureAwait(false); using (var bmp = RndBitmap.RndBmp(RndUtil.ThreadStaticRnd.Next(32) + 96, RndUtil.ThreadStaticRnd.Next(32) + 96)) using (var wsClient = await AsyncWebSocketClient.TryConnectAsync(GetBaseWsUri(host), MaxWsMsgSize, NetworkOpTimeout).ConfigureAwait(false)) { if (wsClient == null) { throw new CheckerException(ExitCode.DOWN, "ws connect failed"); } await Console.Error.WriteLineAsync("ws connected").ConfigureAwait(false); if (await wsClient.TryWaitMessageAsync(buffer => Tuple.Create(buffer.Count == 2 && buffer.Array[0] == (byte)'h' && buffer.Array[1] == (byte)'i', buffer), NetworkOpTimeout).ConfigureAwait(false) == default(ArraySegment <byte>)) { throw new CheckerException(ExitCode.MUMBLE, "await hello failed"); } await Console.Error.WriteLineAsync("ws hello received").ConfigureAwait(false); // ReSharper disable once AccessToDisposedClosure var wsTask = Task.Run(() => wsClient.TryWaitMessageAsync(buffer => { if (!ProtoBufHelper.TryDeserialize <Transmission>(buffer, out var transmission)) { throw new CheckerException(ExitCode.MUMBLE, "invalid ws data"); } return(Tuple.Create(transmission.Name == b64Name, transmission)); }, NetworkOpTimeout)); await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var httpClient = new AsyncHttpClient(GetBaseHttpUri(host)); var result = await httpClient.DoRequestAsync(WebRequestMethods.Http.Put, PutRelative, new WebHeaderCollection { { "X-SG1-Name", b64Name }, { "X-SG1-Entropy", b64Entropy } }, bmp.ToByteArray(), NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"put {PutRelative} failed"); } var key = result.Headers?["X-SG1-Key"]; if (string.IsNullOrEmpty(key)) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response"); } if (!ProtoBufHelper.TryDeserialize(result.Body, out Spectrum spectrum)) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response"); } var expectedSpectrum = bmp.CalcSpectrum(); if (!spectrum.ComponentEquals(expectedSpectrum)) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var msg = await wsTask.ConfigureAwait(false); if (msg == null || msg.Name != b64Name) { throw new CheckerException(ExitCode.MUMBLE, "await msg failed"); } var flagid = $"{b64Name}:{Convert.ToBase64String(Encoding.ASCII.GetBytes(key))}"; await Console.Out.WriteLineAsync(flagid).ConfigureAwait(false); return(flagid); } }