private async Task ConnectAsync() { await _clientWebSocket.ConnectAsync(Uri, _cancellationToken); CallOnConnected(); _messageReceiveWorker = WatchForMessagesFromServer(); }
/// <summary> /// Connects to the WebSocket server. /// </summary> /// <param name="uri">The URI of the WebSocket server.</param> /// <param name="customHeaders">Custom headers to send with the request.</param> /// <returns></returns> public override async Task ConnectAsync(Uri uri, IReadOnlyDictionary <string, string> customHeaders = null) { SocketMessageQueue = new ConcurrentQueue <string>(); TokenSource = new CancellationTokenSource(); StreamDecompressor?.Dispose(); CompressedStream?.Dispose(); DecompressedStream?.Dispose(); DecompressedStream = new MemoryStream(); CompressedStream = new MemoryStream(); StreamDecompressor = new DeflateStream(CompressedStream, CompressionMode.Decompress); Socket = new System.Net.WebSockets.Managed.ClientWebSocket(); Socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); if (Proxy != null) // because mono doesn't implement this properly { Socket.Options.Proxy = Proxy; } if (customHeaders != null) { foreach (var kvp in customHeaders) { Socket.Options.SetRequestHeader(kvp.Key, kvp.Value); } } await Socket.ConnectAsync(uri, Token).ConfigureAwait(false); await OnConnectedAsync().ConfigureAwait(false); WsListener = Task.Run(ListenAsync, Token); }
private static async Task <WebSocket> WebSocketFactory(Uri url, IConnectionOptions options, CancellationToken cancellationToken) { var ws = new System.Net.WebSockets.Managed.ClientWebSocket(); await ws.ConnectAsync(url, cancellationToken); return(ws); }
public async Task <string> Connect(string uri) { string key = string.Empty; try { webSocket = new System.Net.WebSockets.Managed.ClientWebSocket(); await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None); key = await ReceiveFirst(); receiveAction.Debug(!string.IsNullOrEmpty(key) ? $"WebSocket Connect Success:{key},Server excute logs will accept from websocket" : $"WebSocket Connect Fail,Server excute logs will accept from http request"); if (!string.IsNullOrEmpty(key)) { mDetectionTimer = new System.Threading.Timer(Ping, null, 1000 * 2, 1000 * 2); } new Task(async() => { try { await Receive(); } catch (Exception) { try { webSocket.Dispose(); } catch (Exception) { } } }).Start(); new Task(() => { try { ReceiveHttp(); } catch (Exception) { } }).Start(); } catch (Exception e) { //ignore receiveAction.Debug($"WebSocket Connect[{uri}] Fail:" + e); receiveAction.Debug($"WebSocket Connect Fail,Server excute logs will accept from http request"); } if (string.IsNullOrEmpty(key)) { key = await ReceiveFirst(); } return(key); }
private async Task <Browser> CreateWebBrowser(string ChromePath) { async Task <WebSocket> CreateWebSocketTask(Uri url, IConnectionOptions options, CancellationToken cancellationToken) { var result = new System.Net.WebSockets.Managed.ClientWebSocket(); result.Options.KeepAliveInterval = TimeSpan.Zero; await result.ConnectAsync(url, cancellationToken).ConfigureAwait(false); return(result); } var downloadChrome = string.IsNullOrEmpty(ChromePath) || !File.Exists(ChromePath); if (downloadChrome) { Debug.Write("downloading Chrome..."); var browserFetcherOptions = new BrowserFetcherOptions { Path = $"{AppDomain.CurrentDomain.BaseDirectory}", Platform = Platform.Win64, Product = Product.Chrome }; var browserFetcher = new BrowserFetcher(browserFetcherOptions); var revisionInfo = await browserFetcher.DownloadAsync(); ChromePath = revisionInfo.ExecutablePath; // set the created chrome path Debug.WriteLine("done!"); } var launchOptions = new LaunchOptions { Headless = false, Timeout = (10 * 1000), // 10 sec ExecutablePath = ChromePath, /// $"{AppDomain.CurrentDomain.BaseDirectory}Win64-884014\\chrome-win\\chrome.exe", DefaultViewport = null, // max resolution IgnoreHTTPSErrors = true, Args = new[] { "--no-sandbox", "--disable-gpu" } // "--window-size=800,1080" }; if (Environment.OSVersion.Version.Major < 10) { launchOptions.WebSocketFactory = CreateWebSocketTask; // support for windows-7 } var browser = await Puppeteer.LaunchAsync(launchOptions); return(browser); }
public async Task Connect() { try { Log.Debug("Connecting to " + url); if (ws != null && (ws.State == System.Net.WebSockets.WebSocketState.Aborted || ws.State == System.Net.WebSockets.WebSocketState.Closed)) { ws.Dispose(); ws = null; // ws = new ClientWebSocket(); // ws = (ClientWebSocket)SystemClientWebSocket.CreateClientWebSocket(); ws = new System.Net.WebSockets.Managed.ClientWebSocket(); src = new CancellationTokenSource(); } if (ws == null) { // ws = new ClientWebSocket(); // ws = (ClientWebSocket)SystemClientWebSocket.CreateClientWebSocket(); ws = new System.Net.WebSockets.Managed.ClientWebSocket(); src = new CancellationTokenSource(); } if (ws.State == System.Net.WebSockets.WebSocketState.Connecting || ws.State == System.Net.WebSockets.WebSocketState.Open) { return; } if (ws.State == System.Net.WebSockets.WebSocketState.CloseReceived) { OnClose?.Invoke("Socket closing"); ws.Dispose(); ws = null; return; } await ws.ConnectAsync(new Uri(url), src.Token); Log.Information("Connected to " + url); Task receiveTask = Task.Run(async() => await receiveLoop(), src.Token); Task pingTask = Task.Run(async() => await PingLoop(), src.Token); OnOpen?.Invoke(); } catch (Exception ex) { Log.Error(ex, ""); OnClose?.Invoke(ex.Message); } }
public Task ConnectAsync() { _tokenSource = new CancellationTokenSource(); Uri wsUri = _urlConverter.HttpToWs(_uri, EIO.ToString(), Path, Parameters); if (_socket != null) { _socket.Dispose(); } _socket = new System.Net.WebSockets.Managed.ClientWebSocket(); bool executed = _socket.ConnectAsync(wsUri, CancellationToken.None).Wait(ConnectTimeout); if (!executed) { throw new TimeoutException(); } Listen(); return(Task.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="uri"></param> /// <param name="options"></param> /// <exception cref="TimeoutException"></exception> /// <exception cref="WebSocketException"></exception> /// <returns></returns> public async Task ConnectAsync(Uri uri) { if (_ws != null) { _ws.Dispose(); } _ws = new System.Net.WebSockets.Managed.ClientWebSocket(); Config?.Invoke(_ws.Options); _wsWorkTokenSource = new CancellationTokenSource(); var wsConnectionTokenSource = new CancellationTokenSource(_io.Options.ConnectionTimeout); try { await _ws.ConnectAsync(uri, wsConnectionTokenSource.Token); _ = Task.Run(ListenAsync); } catch (TaskCanceledException) { throw new TimeoutException(); } }
static async Task TestConnection(string server) { using (var ws = new System.Net.WebSockets.Managed.ClientWebSocket()) { await ws.ConnectAsync(new Uri(server), CancellationToken.None); var buffer = new ArraySegment <byte>(new byte[1024]); var readTask = ws.ReceiveAsync(buffer, CancellationToken.None); const string msg = "hello"; var testMsg = new ArraySegment <byte>(Encoding.UTF8.GetBytes(msg)); await ws.SendAsync(testMsg, WebSocketMessageType.Text, true, CancellationToken.None); var read = await readTask; var reply = Encoding.UTF8.GetString(buffer.Array, 0, read.Count); if (reply != msg) { throw new Exception($"Expected to read back '{msg}' but got '{reply}' for server {server}"); } Console.WriteLine("Success connecting to server " + server); } }
public void Connect() { Task task = ws.ConnectAsync(serverUri, CancellationToken.None); task.Wait(); }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { ConfigOptions?.Invoke(_ws.Options); await _ws.ConnectAsync(uri, cancellationToken).ConfigureAwait(false); }
/// <summary> /// 语音转写一个完整的音频文件 /// </summary> /// <param name="data"></param> /// <returns></returns> public async Task <ResultModel <string> > ConvertAudio(byte[] data) { try { using (_ws = new ClientWebSocket()) { Status = ServiceStatus.Running; _host = ApiAuthorization.BuildAuthUrl(_settings); await _ws.ConnectAsync(new Uri(_host), CancellationToken.None); _receiveTask = StartReceiving(_ws); //开始发送数据 for (int i = 0; i < data.Length; i += _frameSize) { byte[] buffer = SubArray(data, i, _frameSize); if (buffer == null || data.Length - i < _frameSize) { _status = FrameState.Last; //文件读完 } switch (_status) { case FrameState.First: FirstFrameData firstFrame = new FirstFrameData { common = _common, business = _business, data = _data }; firstFrame.data.status = FrameState.First; firstFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(firstFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); _status = FrameState.Continue; break; case FrameState.Continue: //中间帧 ContinueFrameData continueFrame = new ContinueFrameData { data = _data }; continueFrame.data.status = FrameState.Continue; continueFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(continueFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); break; case FrameState.Last: // 最后一帧音频 LastFrameData lastFrame = new LastFrameData { data = _data }; lastFrame.data.status = FrameState.Last; lastFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(lastFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); break; } await Task.Delay(_intervel); } while (_receiveTask.Status != TaskStatus.RanToCompletion) { await Task.Delay(10); } await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "NormalClosure", CancellationToken.None); } StringBuilder result = new StringBuilder(); foreach (var item in _result) { result.Append(item.data); } ResetState(); return(new ResultModel <string>() { Code = ResultCode.Success, Data = result.ToString(), }); } catch (Exception ex) { return(new ResultModel <string>() { Code = ResultCode.Error, Message = ex.Message, }); } }
private async Task <ResultModel <string> > DoFragmentAsr(byte[] data, FrameState state = FrameState.First) { try { if (_ws == null && _status == FrameState.First) { _ws = new ClientWebSocket(); _status = FrameState.First; _host = ApiAuthorization.BuildAuthUrl(_settings); await _ws.ConnectAsync(new Uri(_host), CancellationToken.None); if (_ws.State != WebSocketState.Open) { throw new Exception("Connect to xfyun api server failed."); } _receiveTask = StartReceiving(_ws); } //开始发送数据 for (int i = 0; i < data.Length; i += _frameSize) { byte[] buffer = null; if (_rest.Length == 0) //没有上次分片的数据 { if (data.Length - i < _frameSize) //最后一帧不满一个完整的识别帧,那么加入缓存,下个分片的时候继续使用 { if (state != FrameState.Last) { int length = data.Length - i; Array.Copy(data, i, _rest.Cache, 0, length); _rest.Length = length; } else { buffer = SubArray(data, i, _frameSize); _status = FrameState.Last; } } else { buffer = SubArray(data, i, _frameSize); if (state == FrameState.Last && data.Length - i == _frameSize) { _status = FrameState.Last; if (buffer == null) { buffer = new byte[1] { 0 }; } } } } else //有上次分片的数据 { if (data.Length + _rest.Length <= _frameSize) { buffer = new byte[_rest.Length + data.Length]; Array.Copy(_rest.Cache, 0, buffer, 0, _rest.Length); //最后分片加上缓存不满一个帧大小的情况 Array.Copy(data, i, buffer, _rest.Length, data.Length); _status = FrameState.Last; i = data.Length - _frameSize; } else { buffer = new byte[_frameSize]; Array.Copy(_rest.Cache, 0, buffer, 0, _rest.Length); Array.Copy(data, i, buffer, _rest.Length, _frameSize - _rest.Length); i -= _rest.Length; } _rest.Clear(); //清空 } if (_rest.Length != 0) { break; } switch (_status) { case FrameState.First: FirstFrameData firstFrame = new FirstFrameData { common = _common, business = _business, data = _data }; firstFrame.data.status = FrameState.First; firstFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(firstFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); _status = FrameState.Continue; break; case FrameState.Continue: //中间帧 ContinueFrameData continueFrame = new ContinueFrameData { data = _data }; continueFrame.data.status = FrameState.Continue; continueFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(continueFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); break; case FrameState.Last: // 最后一帧音频 LastFrameData lastFrame = new LastFrameData { data = _data }; lastFrame.data.status = FrameState.Last; lastFrame.data.audio = System.Convert.ToBase64String(buffer); await _ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(lastFrame))) , WebSocketMessageType.Text , true , CancellationToken.None); break; } await Task.Delay(_intervel); } if (state == FrameState.Last) { while (_receiveTask.Status != TaskStatus.RanToCompletion) { await Task.Delay(10); } await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "NormalClosure", CancellationToken.None); } return(new ResultModel <string>() { Code = ResultCode.Success, Data = null, }); } catch (Exception ex) { //服务器主动断开连接或者自动断开连接了 if (ex.Message.ToLower().Contains("unable to read data from the transport connection")) { try { await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "NormalClosure", CancellationToken.None); } catch { } while (_receiveTask.Status != TaskStatus.RanToCompletion) { await Task.Delay(10); } return(new ResultModel <string>() { Code = ResultCode.Disconnect, Message = "服务器主动断开连接,可能是整个会话是否已经超过了60s、读取数据超时、静默检测超时等原因引起的。", }); } else { return(new ResultModel <string>() { Code = ResultCode.Error, Message = ex.Message, }); } } }
public async Task ConnectAsync(string socketServer) => await _clientWebSocket.ConnectAsync(new Uri(socketServer), CancellationToken.None) .ConfigureAwait(false);
//private async Task<WebSocketReceiveResult> SendCmdAsync(CdpMsg msg) private async Task <string> SendCmdAsync(CdpMsg msg) { try { using (ClientWebSocket ws = new ClientWebSocket()) { Log($"CdpClient.SendMsg(): Attempting to send cmd {msg.method}, port is {_chromeDebuggingPort}"); // load config await CdpConfig.LoadConfigAsync().ConfigureAwait(false); byte[] receiveBytes = new byte[65536]; var receiveBuffer = new ArraySegment <byte>(receiveBytes); ws.Options.SetBuffer(65536, 65536); // (receive 64KB, send 64KB) #if DEBUG var tokenSource = new CancellationTokenSource(600000); // 10 mins #else var tokenSource = new CancellationTokenSource(10000); // 10 secs #endif CancellationToken cancellationToken = tokenSource.Token; Uri wsUri; if (msg.method.StartsWith("Browser")) { wsUri = this.CdpConfig.BrowserWsUri; } else { wsUri = this.CdpConfig.PageWsUri; } Log($"CdpClient.SendMsg(): Attempting to connect to uri {wsUri}, port is {_chromeDebuggingPort}..."); await ws.ConnectAsync(wsUri, cancellationToken).ConfigureAwait(false); Log($"CdpClient.SendMsg(): ...Connected to to uri {wsUri}, port is {_chromeDebuggingPort}"); string json = Json.Serialize <CdpMsg>(msg); byte[] bytes = Encoding.UTF8.GetBytes(json); ArraySegment <byte> sendBuffer = new ArraySegment <byte>(bytes); Log($"About to send CDP cmd {msg.method} to port {_chromeDebuggingPort}..."); await ws.SendAsync(sendBuffer, WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false); WebSocketReceiveResult result = await ws.ReceiveAsync(receiveBuffer, cancellationToken).ConfigureAwait(false); Log($"...received CDP result for cmd {msg.method}, result = {Json.Serialize(result)}, port is {_chromeDebuggingPort}"); // retrive result from buffer if (result.MessageType != WebSocketMessageType.Text) { return($"Unexpected message type: {result.MessageType}"); } string msgText = Encoding.UTF8.GetString(receiveBytes, 0, result.Count); Log($"{msg.method}(): returned result {msgText}, port is {_chromeDebuggingPort}"); return(msgText); } } catch (Exception ex) { Log($"Exception occurred: {ex.ToString()}"); return(null); } }