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();
}