C#实现ClientWebSocket请求服务端,接收完所有返回值,解决接收数据不全

csharp 复制代码
        private  async Task ConnectWebSocketAsync(Uri serverUri)
        {
            using (ClientWebSocket client = new ClientWebSocket())
            {
                await client.ConnectAsync(serverUri, CancellationToken.None);
               // Console.WriteLine("Connected to WebSocket server.");
                AddTextToRichTextBox1("Connected to WebSocket server.", Color.Green);
                // 发送数据到服务器  
              //  string messageToSend = "Hello, WebSocket server!";

                string messageToSend = GetNewtaken();

                byte[] bytesToSend = Encoding.UTF8.GetBytes(messageToSend);
                await client.SendAsync(new ArraySegment<byte>(bytesToSend), WebSocketMessageType.Text, true, CancellationToken.None);
              //  Console.WriteLine($"Sent: {messageToSend}");
                AddTextToRichTextBox1($"Sent: {messageToSend}", Color.Green);
                // 接收来自服务器的数据  
                byte[] buffer = new byte[1024 * 4];
                WebSocketReceiveResult result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                string messageReceived = Encoding.UTF8.GetString(buffer, 0, result.Count);
               // Console.WriteLine($"Received: {messageReceived}");
                AddTextToRichTextBox1($"Received: {messageReceived}", Color.Green);


                JObject jo_tacken = (JObject)JsonConvert.DeserializeObject(messageReceived);

                string token = "";
                string groups = "";


                string token_str2 = jo_tacken["status"].ToString();
                if (token_str2.Equals("0"))
                {
                    token = jo_tacken["data"][0]["token"].ToString();
                    groups = jo_tacken["data"][0]["groups"][0]["groupid"].ToString();

                    company_connected = true;

                    AddTextToRichTextBox1("本地人脸机设备IP:" + company_face_device_ipAddress + "  端口号:" + company_face_device_port + "连接成功!", Color.Red);
                    LabelTitle("本地人脸");

                    //注册公司人脸成功


                    AddTextToRichTextBox1("获取Token成功:"+ token, Color.Red);



                }
                else
                {
                    AddTextToRichTextBox1("获取Token失败:" + token, Color.Red);
                    AddTextToRichTextBox1("本地人脸设备IP:" + company_face_device_ipAddress + "  端口号:" + company_face_device_port + "连接失败!", Color.Red);
                    LabelTitleFail("连接本地人脸失败!");
                }


                string pageNo = "" + 1;
                // string SizeRow = "" + pageSize;
                string SizeRow = "1000";
                DateTime selectedDate1 = DateEdit1.DateTime;
                DateTime selectedDate2 = DateEdit2.DateTime;
                string startTime = selectedDate1.ToString("yyyy-MM-dd HH:mm:ss");
                string endTime = selectedDate2.ToString("yyyy-MM-dd HH:mm:ss");


                string messageToSend2 = GetGroupStr(token, groups, pageNo, SizeRow, startTime, endTime);
                //  Person[] people = GetFaceInfoByGroup(data[0], company_organization_no, pageNo, SizeRow, startTime, endTime);

                //再发送
                string messageToSend2 = GetNewtaken();
                ------------
                //byte[] bytesToSend2 = Encoding.UTF8.GetBytes(messageToSend2);


                //await client.SendAsync(new ArraySegment<byte>(bytesToSend2), WebSocketMessageType.Text, true, CancellationToken.None);
                  Console.WriteLine($"Sent: {messageToSend}");
                //AddTextToRichTextBox1($"Sent2: {messageToSend2}", Color.Green);
                 接收来自服务器的数据  4KB缓冲区  1024 * 4
                //byte[] buffer2 = new byte[1024 * 900000];
                //WebSocketReceiveResult result2 = await client.ReceiveAsync(new ArraySegment<byte>(buffer2), CancellationToken.None);


                //string messageReceived2 = Encoding.UTF8.GetString(buffer2, 0, result2.Count);
                 Console.WriteLine($"Received: {messageReceived}");
                //AddTextToRichTextBox1($"Received2: {messageReceived2}", Color.Green);
                //------------
                // 使用StreamReader逐行读取响应内容
                //using (Stream stream = await response.Content.ReadAsStreamAsync(), reader = new StreamReader(stream))
                //{
                //    while (!reader.EndOfStream)
                //    {
                //        string line = await reader.ReadLineAsync();
                //        Console.WriteLine(line);
                //    }
                //}
                // 关闭连接  
                // await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                // Console.WriteLine("WebSocket connection closed.");

               // string messageToSend2 = GetNewtaken();
               
                byte[] bytesToSend2 = Encoding.UTF8.GetBytes(messageToSend2);


                //string messageToSend2 = "Your command here";
                //byte[] bytesToSend2 = Encoding.UTF8.GetBytes(messageToSend2);
                await client.SendAsync(new ArraySegment<byte>(bytesToSend2), WebSocketMessageType.Text, true, CancellationToken.None);
                AddTextToRichTextBox1($"Sent: {messageToSend2}", Color.Green);
                // 接收来自服务器的数据
                StringBuilder receivedMessage = new StringBuilder();
                byte[] buffer2 = new byte[1024*4]; // 4KB 缓冲区
                WebSocketReceiveResult result2;

                do
                {
                    result2 = await client.ReceiveAsync(new ArraySegment<byte>(buffer2), CancellationToken.None);
                    if (result2.Count > 0)
                    {
                        string partialMessage = Encoding.UTF8.GetString(buffer2, 0, result2.Count);
                        receivedMessage.Append(partialMessage);
                    }
                } while (!result2.EndOfMessage);

                string messageReceived2 = receivedMessage.ToString();
                AddTextToRichTextBox1($"Received2:", Color.Green);
                AddTextToRichTextBox1(messageReceived2, Color.Green);


                AddTextToRichTextBox1("WebSocket connection closed.", Color.Green);
            }
        }

        public void TestRequest()
        {
           // Uri serverUri = new Uri("wss://example.com/websocket"); // 替换为你的WebSocket服务器URI  
            Uri serverUri = new Uri("ws://192.168.1.1:8080"); // 替换为你的WebSocket服务器URI  
            Task.Run(() => ConnectWebSocketAsync(serverUri)).GetAwaiter().GetResult();
        }
相关推荐
步、步、为营2 小时前
C# 与.NET 日志变革:JSON 让程序“开口说清话”
c#·json·.net
漫漫进阶路5 小时前
VS C++ 配置OPENCV环境
开发语言·c++·opencv
BinaryBardC6 小时前
Swift语言的网络编程
开发语言·后端·golang
code_shenbing6 小时前
基于 WPF 平台使用纯 C# 制作流体动画
开发语言·c#·wpf
code_shenbing6 小时前
基于 WPF 平台实现成语游戏
游戏·c#·wpf
邓熙榆6 小时前
Haskell语言的正则表达式
开发语言·后端·golang
ac-er88887 小时前
Yii框架中的队列:如何实现异步操作
android·开发语言·php
马船长7 小时前
青少年CTF练习平台 PHP的后门
开发语言·php
hefaxiang8 小时前
【C++】函数重载
开发语言·c++·算法
落幕9 小时前
C语言-构造数据类型
c语言·开发语言