Ejemplo n.º 1
0
        private async Task WatchForMessagesFromServer()
        {
            var buffer = new byte[ReceiveChunkSize];

            try
            {
                while (_ws.State == WebSocketState.Open)
                {
                    var stringResult = new StringBuilder();


                    WebSocketReceiveResult result;
                    do
                    {
                        result = await _ws.ReceiveAsync(new ArraySegment <byte>(buffer), _cancellationToken);

                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                            CallOnDisconnected();
                        }
                        else
                        {
                            var str = Encoding.UTF8.GetString(buffer, 0, result.Count);
                            stringResult.Append(str);
                        }
                    } while (!result.EndOfMessage);

                    CallOnMessage(stringResult);
                }
            }
            catch (Exception)
            {
                CallOnDisconnected();
            }
            finally
            {
                _ws.Dispose();
            }
        }
        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);
            }
        }
Ejemplo n.º 3
0
        private async void StartReceiving(ClientWebSocket client)
        {
            if (_result != null)
            {
                _result.Clear();
            }
            //单次完整数据
            string msg = "";

            while (true)
            {
                try
                {
                    if (client.CloseStatus == WebSocketCloseStatus.EndpointUnavailable ||
                        client.CloseStatus == WebSocketCloseStatus.InternalServerError ||
                        client.CloseStatus == WebSocketCloseStatus.EndpointUnavailable)
                    {
                        Status = ServiceStatus.Stopped;
                        return;
                    }
                    //唔,足够大的缓冲区
                    var array   = new byte[100000];
                    var receive = await client.ReceiveAsync(new ArraySegment <byte>(array), CancellationToken.None);

                    if (receive.MessageType == WebSocketMessageType.Text)
                    {
                        if (receive.Count <= 0)
                        {
                            continue;
                        }

                        //string msg = Encoding.UTF8.GetString(array, 0, receive.Count);
                        //在Winform中无法把json一次完整接收,需要判断EndOfMessage的状态。
                        //临时不完整数据
                        string tempMsg = Encoding.UTF8.GetString(array, 0, receive.Count);
                        msg += tempMsg;
                        if (receive.EndOfMessage == false)
                        {
                            continue;
                        }

                        TTSResult result = JsonSerializer.Deserialize <TTSResult>(msg, new JsonSerializerOptions()
                        {
                            PropertyNameCaseInsensitive = true
                        });

                        //清空数据
                        msg = "";

                        if (result.Code != 0)
                        {
                            throw new Exception($"Result error: {result.Message}");
                        }
                        if (result.Data == null)
                        {
                            //空帧,不用管
                            continue;
                        }
                        byte[] audiaBuffer = System.Convert.FromBase64String(result.Data.Audio);
                        _result.AddRange(audiaBuffer);

                        OnMessage?.Invoke(this, result.Data.Audio);

                        if (result.Data.Status == 2)
                        {
                            Status = ServiceStatus.Stopped;
                        }
                    }
                }
                catch (WebSocketException)
                {
                    Status = ServiceStatus.Stopped;
                    return;
                }
                catch (Exception ex)
                {
                    Status = ServiceStatus.Stopped;
                    if (!ex.Message.ToLower().Contains("unable to read data from the transport connection"))
                    {
                        OnError?.Invoke(this, new ErrorEventArgs()
                        {
                            Code      = ResultCode.Error,
                            Message   = ex.Message,
                            Exception = ex,
                        });
                    }
                }
            }
        }