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();
        }
相关推荐
洪大宇11 分钟前
Vuestic 整理使用
开发语言·javascript·ecmascript
WangMing_X13 分钟前
C# 单个函数实现各进制数间转换
java·开发语言·算法·c#·winform·软件
墨染新瑞23 分钟前
C语言——八股文(笔试面试题)
c语言·开发语言
好青崧40 分钟前
JavaScript 循环与条件判断
开发语言·javascript·udp
进步哥44 分钟前
python之爬虫遇到返回内容乱码
开发语言·爬虫·python
ou.cs1 小时前
c# 实现文件更新通知
c#
只看见而已1 小时前
锁升级及线程池相关
java·开发语言
混迹网络的权某2 小时前
每天一道C语言精选编程题之计算天数
c语言·开发语言·考研·算法·改行学it
ChinaDragonDreamer2 小时前
HarmonyOS:自定义组件冻结功能
开发语言·harmonyos·鸿蒙
2301_807083152 小时前
java-数据结构
java·开发语言·数据结构