定义类中的异步方法
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
{
///
/// 客户端的通讯公共类对象
///
public class WindowsOSHelperUtils
{
///
/// Socket通讯的url
///
//public static string Url = "ws://192.168.1.11:1234/";
public static async Task
{
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
string returnValue = await GetAsyncValue(cln);//异步方法
return returnValue;
}
public static async Task
{
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri(FunctionBaseClass.SocketUrl), new CancellationToken()).Wait();
byte[] bytess = Encoding.Default.GetBytes($"asses");
cln.SendAsync(new ArraySegment
string returnValue = await GetAsyncValue(cln);//异步方法
return returnValue;
}
public static async Task
{
//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
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[] bytes2 = new byte[1000 * 500];
// //var webSocketReceiveResult = cln.ReceiveAsync(new ArraySegment
// //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 returnValue = null;
ArraySegment
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;