定义类中的异步方法

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. bzoj 2726 任务安排(3)/loj 10184-10186 斜率优化

    任务安排1 #include<bits/stdc++.h> #define int long long using namespace std; ; int n,s,t[N],c[N],f ...

  2. MVC数据库连接

    创建数据库 创建表 来源:http://blog.csdn.net/tkdwave520/article/details/44629903 <pre  name = “code”  class ...

  3. mybatis的两个核心对象SqlSessionFactory和SqlSession对象

    mybatis的两个核心对象SqlSessionFactory和SqlSession对象 参见:https://www.cnblogs.com/wxdestiny/p/9743686.html

  4. Linux之增加系统调用[内核编译]

    声明:如需引用或者摘抄本博文源码或者其文章的,请在显著处注明,来源于本博文/作者,以示尊重劳动成果,助力开源精神.也欢迎大家一起探讨,交流,以共同进步- 0.0 由于操作系统实验的缘故,有一个实验需要 ...

  5. python中读取mongodb数据并保存为csv格式的文件

    import pandas as pd import matplotlib.pyplot as plt import pymongo %matplotlib inline # 连接mongodb数据库 ...

  6. JQuery常见事件

    ##### 事件 onclick 单机事件 ondblclick 双击事件 onmouseover 鼠标穿过 (子盒子独立) onmouseout 鼠标出去 onmouseenter 鼠标进入 (子盒 ...

  7. Shiro入门 - 通过ini文件进行授权

    shiro-permission.ini #用户 [users] #admin的密码是111111,此用户具有role1.role2两个角色 admin=111111,role1,role2 zhan ...

  8. .Net core 使用特性Attribute验证Session登陆状态

    1.新建一个.net core mvc项目 2.在Models文件夹下面添加一个类MyAttribute,专门用来保存我们定义的特性 在这里我只写了CheckLoginAttribute用来验证登陆情 ...

  9. Javascript - ExtJs - Window组件

    1.所有组件都可以放入window,此时子组件不需要配置renderTo,只需要将它们作为window的items子项即可. 2.items子项必须先创建,最后创建window,否则子项不会显示. 3 ...

  10. dubbo学习笔记1

    DUBBO入门 官方文档:https://dubbo.gitbooks.io/dubbo-user-book/content/preface/ 服务提供者 项目结构: pom文件: <?xml ...