定义类中的异步方法

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;

WebSocket异步通讯,实时返回数据实例的更多相关文章

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

    第一种方式 // 服务端: //var listener = new HttpListener(); // listener.Prefixes.Add("http://*:8080/&quo ...

  2. WebSocket异步通讯,实时返回数据相关问题论坛

    https://stackoverflow.com/questions/23773407/a-websockets-receiveasync-method-does-not-await-the-ent ...

  3. WebSocketTest 异步通讯,实时返回数据

    using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;usin ...

  4. ECharts访问后台,JSON格式返回数据实例

    完成图 一.页面代码 <%@ page language="java" contentType="text/html; charset=UTF-8" pa ...

  5. ajax返回数据为undefined

    在使用ajax异步请求后台返回数据后,使用console.log(data.message)打印返回数据,显示为undefined.苦恼了很久,终于在网上找到了答案. 先给大家看下异步代码: /*清零 ...

  6. jquery的ajax异步请求接收返回json数据

    http://www.jb51.net/article/51122.htm jquery的ajax异步请求接收返回json数据方法设置简单,一个是服务器处理程序是返回json数据,另一种就是ajax发 ...

  7. .net平台下socket异步通讯(代码实例)

    你应该知道的.net平台下socket异步通讯(代码实例) 1,首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端Client 2,然后添加服务端代码,添加命名空间,界面上 ...

  8. 【Spring学习笔记-MVC-5】利用spring MVC框架,实现ajax异步请求以及json数据的返回

    作者:ssslinppp      时间:2015年5月26日 15:32:51 1. 摘要 本文讲解如何利用spring MVC框架,实现ajax异步请求以及json数据的返回. Spring MV ...

  9. Springboot 项目源码 Activiti6 工作流 vue.js html 跨域 前后分离 websocket即时通讯

    特别注意: Springboot 工作流  前后分离 + 跨域 版本 (权限控制到菜单和按钮) 后台框架:springboot2.1.2+ activiti6.0.0+ mybaits+maven+接 ...

随机推荐

  1. set用法

    set的用法一直拖着,今天才算真正会了,小小总结一下(我好菜啊啊啊) #include<bits/stdc++.h> using namespace std; ]; int main(){ ...

  2. 【D3D】Directx12运行报错&win10无法添加【图形工具】

    “我欢欣雀跃地打开<3D programming with Directx12>,准备接受D3D的洗礼,然后就卡在了 chapter 0 .”——Liez 100%纯小白的chapter ...

  3. 【bzoj 2527】[Poi2011]Meteors

    Description Byteotian Interstellar Union (BIU) has recently discovered a new planet in a nearby gala ...

  4. PHP操作实现一个多功能购物网站

    PHP操作实现一个多功能购物网站 一.需要实现的页面: Index.aspx:浏览商品页面,显示商品列表,用户可以点击“加入购物车“. ViewCart.aspx:查看购物车页面,显示已购买的商品信息 ...

  5. oracle 窗口函数 (keep)

    看到很多人对于keep不理解,这里解释一下! Returns the row ranked first using DENSE_RANK2种取值:DENSE_RANK FIRSTDENSE_RANK  ...

  6. Mysql 基础导入导出

    Mysql 导出数据库: mysqldump -u root -p 数据库 > 导出库名.sql mysqldump -u 用户名 -p 数据库名 表名 > 导出表名.sql 示例:mys ...

  7. python之import模块及包的调用

    模块概念 在Python中,一个.py文件就称之为一个模块(Module).使用模块组织代码,最大的好处是大大提高了代码的可维护性 模块一共三种:python标准库.第三方模块.应用程序自定义模块. ...

  8. java时间计算

  9. ASP.NET MVC - 安全、身份认证、角色授权和ASP.NET Identity

    ASP.NET MVC - 安全.身份认证.角色授权和ASP.NET Identity ASP.NET MVC内置的认证特性 AuthorizeAttribute特性(System.Web.Mvc)( ...

  10. light oj 1254 - Prison Break 最短路

    题目大意:n个点m条边的有向图,q次询问c,s,t,表示汽车邮箱容量为c,求从起点s到终点t的最小费用.汽车在每个点可以加任意的油,每个点的单位油价为a[i]. 题目思路:利用最小费优先队列优化最短路 ...