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();
        }
相关推荐
----云烟----1 小时前
QT中QString类的各种使用
开发语言·qt
lsx2024062 小时前
SQL SELECT 语句:基础与进阶应用
开发语言
开心工作室_kaic2 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
向宇it2 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
武子康2 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
九鼎科技-Leo2 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
转世成为计算机大神3 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式
宅小海3 小时前
scala String
大数据·开发语言·scala
qq_327342733 小时前
Java实现离线身份证号码OCR识别
java·开发语言
锅包肉的九珍3 小时前
Scala的Array数组
开发语言·后端·scala