private async Task ConnectAsync()
        {
            await _ws.ConnectAsync(_uri, _cancellationToken);

            CallOnConnected();
            WatchForMessagesFromServer();
        }
        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);
            }
        }
Exemple #3
0
        public async Task <ResultModel <byte[]> > Convert(string data)
        {
            try
            {
                Status = ServiceStatus.Running;
                //BuildAuthUrl
                string host = ApiAuthorization.BuildAuthUrl(_settings);
                //Base64 convert string
                if (string.IsNullOrEmpty(data))
                {
                    throw new Exception("Convert data is null.");
                }
                string base64Text = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(data));
                if (base64Text.Length > 8000)
                {
                    throw new Exception("Convert string too long. No more than 2000 chinese characters.");
                }

                using (var ws = new ClientWebSocket())
                {
                    await ws.ConnectAsync(new Uri(host), CancellationToken.None);

                    //接收数据
                    StartReceiving(ws);

                    //Send data
                    _data.text = base64Text;
                    TTSFrameData frame = new TTSFrameData()
                    {
                        common   = _common,
                        business = _business,
                        data     = _data
                    };
                    //string send = JsonHelper.SerializeObject(frame);
                    await ws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(frame))), WebSocketMessageType.Text, true, CancellationToken.None);

                    while (Status == ServiceStatus.Running)
                    {
                        await Task.Delay(10);
                    }
                    //await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "NormalClosure", CancellationToken.None);
                    //在Winform中会提示:调用 WebSocket.CloseAsync 后收到的消息类型“Text”无效。只有在不需要从远程终结点得到更多数据时,才应使用 WebSocket.CloseAsync。请改用“WebSocket.CloseOutputAsync”保持能够接收数据,但关闭输出通道。
                    await ws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "NormalClosure", CancellationToken.None);
                }
                return(new ResultModel <byte[]>()
                {
                    Code = ResultCode.Success,
                    Data = _result == null ? null : _result.ToArray(),
                });
            }
            catch (Exception ex)
            {
                //服务器主动断开连接
                if (ex.InnerException != null && ex.InnerException is SocketException && ((SocketException)ex.InnerException).SocketErrorCode == SocketError.ConnectionReset)
                {
                    return(new ResultModel <byte[]>()
                    {
                        Code = ResultCode.Error,
                        Message = "服务器主动断开连接,可能是整个会话是否已经超过了60s、读取数据超时等原因引起的。",
                    });
                }
                else
                {
                    return(new ResultModel <byte[]>()
                    {
                        Code = ResultCode.Error,
                        Message = ex.Message,
                    });
                }
            }
        }