定义类中的异步方法

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. python中矩阵的用法

    python矩阵的表示真是让人头大,下面记录一下具体用法:array是numpy库里的.不管怎样, 一.首先导入 numpy: 1)import numpy 2)from numpy import * ...

  2. artTemplate/template.js模板将时间戳格式化为正常的日期

    1:引用<script type="text/javascript" src="../js/artTemplate/template.js">< ...

  3. Java8新特性(待更新...)

    一.Lambda表达式 二.接口的默认方法与静态方法 三.方法引用 四.重复注解 五.扩展注解的支持 六.Optional 七.Stream 八.Date/Time API (JSR 310) 九.J ...

  4. 添加日志(配置spring)---Java_web

    一.配置日志--以下三部 1.配置web.xml;  2.配置 log4j.properties;  3.配置jar包 以下是文件目录 二.配置 web.xml (注意:下面的classpath即lo ...

  5. STL之heap学习

    C++标准库中的堆-heap make_heap函数,包括两个参数(begin(number),end(number)).(左闭右开) pop_heap函数,包括两个参数,起始位置和终止位置,将当前区 ...

  6. Django学习手册 - 权限管理(一)

    权限管理原理: 不同角色拥有不同的角色权限,所以能否访问的页面也就不相同. 通过控制URL使用户访问到不同的URL,从而达到权限控制的目的. 设计权限数据库 权限管理 from django.db i ...

  7. Service生命周期

    https://www.cnblogs.com/huihuizhang/p/7623760.html (1)Service是单例的,只要没有destroy,多次startService或bindSer ...

  8. ASP.NET MVC - WEB API

    ASP.NET WEB API 与WEB API有关的类型 HttpMessageHandler(System.Net.Http)(消息处理器) 表示Http请求的处理程序,处理程序类似于Http管道 ...

  9. Netty实现简单UDP服务器

    本文参考<Netty权威指南> 文件列表: ├── ChineseProverbClientHandler.java ├── ChineseProverbClient.java ├── C ...

  10. Scala 继承

    1. 继承 Scala 通过 extends 关键字来继承类. 那么继承一个类有什么好处呢? 子类拥有继承自超类的方法和字段(即为val(常量), var(变量)所定义的) 可以添加自己需要的新方法和 ...