WebSocket异步通讯,实时返回数据实例

时间:2024-09-05 16:04:32

定义类中的异步方法

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WindowsServiceTest;

namespace WindowsService
{
/// <summary>
/// 客户端的通讯公共类对象
/// </summary>
public class WindowsOSHelperUtils
{

/// <summary>
/// Socket通讯的url
/// </summary>
//public static string Url = "ws://192.168.1.11:1234/";

public static async Task<string> Login(string name, string no, string level, string imagestring)
{
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri(FunctionBaseClass.SocketUrl), new CancellationToken()).Wait();
byte[] bytess = Encoding.Default.GetBytes($"login#{name}#{no}#{level}#{imagestring}");
cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
string returnValue = await GetAsyncValue(cln);//异步方法
return returnValue;
}

public static async Task<string> EvaluateWithReasons()
{
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri(FunctionBaseClass.SocketUrl), new CancellationToken()).Wait();
byte[] bytess = Encoding.Default.GetBytes($"asses");
cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
string returnValue = await GetAsyncValue(cln);//异步方法
return returnValue;
}

public static async Task<string> FaceValidateWithIdCard()
{
//FaceValidateWithIdCard faceValidateWithIdCard = (FaceValidateWithIdCard)command;
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri(FunctionBaseClass.SocketUrl), new CancellationToken()).Wait();
byte[] bytess = Encoding.Default.GetBytes($"begin");
cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
string returnValue = await GetAsyncValue(cln);//异步方法
return returnValue;
#region MyRegion
//string url = "ws://127.0.0.1:1234/";
//try
//{
// ClientWebSocket cln = new ClientWebSocket();
// cln.ConnectAsync(new Uri(url), new CancellationToken()).Wait();

// byte[] bytess = Encoding.Default.GetBytes("begin#70");
// cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
// byte[] bytes2 = new byte[1000 * 500];
// //var webSocketReceiveResult = cln.ReceiveAsync(new ArraySegment<byte>(bytes2), CancellationToken.None);

// //GetAsyncValue(cln);//异步方法,很关键

// //string xx = Encoding.Default.GetString(bytes2);
// Console.WriteLine("11111111111");
// Console.Read();

//}
//catch (Exception ex)
//{
// string ss = ex.ToString();
// Console.WriteLine(ss);
// //}
// Console.Read();
//}
#endregion
}

public static async Task<string> GetAsyncValue(ClientWebSocket clientWebSocket)
{
string returnValue = null;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await clientWebSocket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
returnValue = reader.ReadToEnd();
//Console.WriteLine(returnValue);
}
}
}
return returnValue;
}
}
}

调用异步方法

string returnvalue = WindowsOSHelperUtils.Login(userName, userNo, "5", byteString).Result;

string returnvalue = WindowsOSHelperUtils.EvaluateWithReasons().Result;

string returnvalue = WindowsOSHelperUtils.FaceValidateWithIdCard().Result;