HttpLitener处理http请求和Websocket请求的案例具体步骤如下

1、新建控制台项目TestClientWebsocket

2、选择项目右键添加类HttpAndWebsocket,代码如下

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

namespace TestClientWebsocket
{
public class HttpAndWebsocket
{
public async void Start(string url)
{
string url1 = "http://+:80/";
int Port = 1234;
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add("http://+:" + Port + "/");//注:其中//和:之间的+是代表本机的所有ip
httpListener.Start();
while (true)
{
try
{
HttpListenerContext httpListenerContext = await httpListener.GetContextAsync();
try
{
if (httpListenerContext.Request.IsWebSocketRequest)
{
ProcessRequest(httpListenerContext);
}
}
catch (Exception)
{
httpListenerContext.Response.StatusCode = 400;
httpListenerContext.Response.Close();
}
}
catch (Exception)
{
throw;
}
}
}

private async void ProcessRequest(HttpListenerContext listenerContext)
{
HttpListenerWebSocketContext httpListenerWebSocket;

try
{
httpListenerWebSocket = await listenerContext.AcceptWebSocketAsync(null);
}
catch (Exception)
{
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
return;
}
WebSocket webSocket = httpListenerWebSocket.WebSocket;
try
{

while (webSocket.State == WebSocketState.Open)
{
byte[] returnBytes = new byte[10240];
WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(returnBytes), CancellationToken.None);
string ReceivesData = Encoding.UTF8.GetString(returnBytes, 0, webSocketReceiveResult.Count);
ReceivesData = $"我已经收到数据:{ReceivesData}";
returnBytes = Encoding.UTF8.GetBytes(ReceivesData);
await webSocket.SendAsync(new ArraySegment<byte>(returnBytes), WebSocketMessageType.Text, true, CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(3));
}
}
catch (Exception)
{

throw;
}
finally
{
if (webSocket != null)
{
webSocket.Dispose();
}
}
}

}
}

4、控制台的Program.cs中代码

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;

namespace TestClientWebsocket
{
class Program
{
public static string SocketUrl = "ws://127.0.0.1:1234/";
//public static string SocketUrl = "ws://192.168.1.202:8081/ws?id=";

static void Main(string[] args)
{

//启动Websocket服务
HttpAndWebsocket httpAndWebsocket = new HttpAndWebsocket();
httpAndWebsocket.Start(SocketUrl);

//启动ClientWebsocket客户端

for (int i = 0; i < 2; i++)
{

System.Threading.Tasks.Task.Factory.StartNew(BBB, i);

}

Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();

//string name = Console.ReadLine();
//string no = Console.ReadLine();
//string level = Console.ReadLine();
//string imagestring = Console.ReadLine();
//string returnvalue = Login(name, no, level, imagestring).Result;
//string returnvalue = Login("22", "22", "22", "22").Result;

//for (int i = 0; i < 2; i++)
//{
// //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));

// //System.Threading.Tasks.Task.Factory.StartNew(BBB, i);
// Task.Delay(2000);
// TestWebsocket testWebsocket = new TestWebsocket("ws://127.0.0.1:1234/", i.ToString(), "1", "1", "1");
// testWebsocket.showmeg = Addlog;
// testWebsocket.Satart();

//}

//System.Threading.Tasks.Task.Factory.StartNew(BBB, 66);
//Console.WriteLine($"{returnvalue}");
//returnvalue = Login("33", "33", "33", "33").Result;
//Console.WriteLine($"{returnvalue}");
Console.Read();

//string returnvalue = TestWebsocket.EvaluateWithReasons().Result;

//string returnvalue = TestWebsocket.FaceValidateWithIdCard().Result;
}

public static async void BBB(object i)
{
string x = $"这是第{i}个。。。";
//ClientWebSocket cln = new ClientWebSocket();
//cln.ConnectAsync(new Uri(SocketUrl), new CancellationToken()).Wait();
//byte[] bytess = Encoding.Default.GetBytes($"111");
//cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
//string returnValue = await GetAsyncValue(cln);//异步方法
//Console.WriteLine($"{returnValue}");
try
{
ClientWebSocket cln = new ClientWebSocket();
await cln.ConnectAsync(new Uri(SocketUrl + i.ToString()), new CancellationToken());
string returnvalue = await Login(cln, "1", "1", "1", "1");
Console.WriteLine($"{returnvalue}");

//string returnvalue = await TestClientWebsocket.TestWebsocket.Login("1", "1", "1", "1");
//Console.WriteLine($"{returnvalue}");
}
catch (Exception ex)
{
throw ex;
}

}

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

public static async Task<string> GetAsyncValue(ClientWebSocket clientWebSocket)
{
string returnValue = null;
byte[] buffer = new byte[10240];
WebSocketReceiveResult result = null;
//while (clientWebSocket.State == WebSocketState.Open)
//{
result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
returnValue = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine(returnValue);
}
return returnValue;
}

}
}

HttpLitener处理http请求和Websocket请求的更多相关文章

  1. Ajax中get请求和post请求

    我们在使用Ajax向服务器发送数据时,可以采用Get方式请求服务器,也可以使用Post方式请求服务器,那么什么时候该采用Get方式,什么时候该采用Post方式呢? Get请求和Post请求的区别: 1 ...

  2. slave IO流程之二:注册slave请求和dump请求

    slave IO流程已经在http://www.cnblogs.com/onlyac/p/5815566.html中有介绍 这次我们要探索注册slave请求和dump请求的报文格式和主要流程. 一.注 ...

  3. loadrunner录制脚本如何选择使用get请求和post请求的方式

    在loadrunner工具里录制脚本时常常会用到get请求和post请求,有关loadrunner常用的这两类的请求主要有: get请求: web_url 和 web_link post请求: web ...

  4. iOS开发网络篇—GET请求和POST请求

    iOS开发网络篇—GET请求和POST请求 一.GET请求和POST请求简单说明 创建GET请求 // 1.设置请求路径 NSString *urlStr=[NSString stringWithFo ...

  5. 普通请求和ajax请求的区别

    普通请求和ajax请求的区别? 下面的action返回一个json文件,文件内容为sts.*,data1

  6. iOS开发网络篇—GET请求和POST请求(转)

    一.GET请求和POST请求简单说明 创建GET请求 1 // 1.设置请求路径 2 NSString *urlStr=[NSString stringWithFormat:@"http:/ ...

  7. GET请求和POST请求的区别

    request获取请求参数 最为常见的客户端传递参数方式有两种: 浏览器地址栏直接输入:一定是GET请求: 超链接:一定是GET请求: 表单:可以是GET,也可以是POST,这取决与<form& ...

  8. 使用SoapUI工具做get请求和post请求接口测试

    祝大家节日快乐啦. 之前写过的一篇帖子已经介绍了SoapUI工具的基本使用,所以在此不再重复讲解关于建工程.建测试套件.添加用例等操作,可查看该篇文章详解:http://www.cnblogs.com ...

  9. Ajax相关——get请求和post请求的区别

    一.完整的URL由以下几部分组成: scheme:通信协议,常用的有:http/ftp. host:主机,服务器(计算机)域名或IP地址 port:端口,整数,可选,省略时使用默认端口,http的默认 ...

随机推荐

  1. 微信小程序分享小程序码的生成,多参数以及参数的获取

    如果本文对你有用,请爱心点个赞,提高排名,帮助更多的人.谢谢大家!❤ 如果解决不了,可以在文末进群交流. 官方文档地址:https://developers.weixin.qq.com/minipro ...

  2. Docker -compose install Harbor

    Docker-compose Harbor install Docker install Yum install docker-compose 首先安装 yum configuation 管理工具 [ ...

  3. SpringBoot 中的使用事务

    转自:https://blog.csdn.net/linzhiqiang0316/article/details/52638039 什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数 ...

  4. linu学习记录--初学linux中的几个基本命令以及比较关键的man指令

    import chardet chardet.detect() #传入参数可以输出查看参数的对应编码 首先是用decode将对象编码转换成unicode,然后用encode将对象编码转换成输出所需,u ...

  5. 时间模块time和datetime的使用

    日期和时间 一 time模块 import time 时间的表示形式: 时间戳 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现 ...

  6. TLS 1.3 中Pre_shared_key和key_share对应的两种密钥交换模式

    1.TLS1.3的整个协议的文档规范 请参照 RFC 8846,协议规范中指出,TLS1.3提供三方面的安全属性,分别是身份认证.通信加密.完整性验证. 2.TLS1.3协议主要包括两个组成部分,分别 ...

  7. PCM音频数据格式介绍

    http://blog.csdn.net/ljxt523/article/details/52068241 1. What is PCM? PCM(Pulse-code-modulation)是模拟信 ...

  8. Linux磁盘管理——BIOS和UEFI

    参考:BIOS and UEFI - CompTIA A+ 220-901 - 1.1 BIOS and UEFI As Fast As Possible 严格上来说BIOS和UEFI除了在搜索boo ...

  9. Elasticsearch 术语介绍和CRUD实际操作入门

    一.Elastic Stack 核心Elasticsearch Elasticsearch 是一个分布式.RESTful 风格的搜索和数据分析引擎.Elasticsearch 是面向文档的,这就意味着 ...

  10. wireshark 抓包再利用TCP socket发送包里的payload是可以实现登陆的

    用户密码可被批量破解 在用户使用手机端登录时,对数据进行抓包分析. 多次抓包分析后,可得到几个关键TCP数据包. 根据前面逆向编写出的解密算法,使用socket进行数据发包测试: 可以模拟APK进行用 ...