HttpLitener处理http请求和Websocket请求
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请求的更多相关文章
- Ajax中get请求和post请求
我们在使用Ajax向服务器发送数据时,可以采用Get方式请求服务器,也可以使用Post方式请求服务器,那么什么时候该采用Get方式,什么时候该采用Post方式呢? Get请求和Post请求的区别: 1 ...
- slave IO流程之二:注册slave请求和dump请求
slave IO流程已经在http://www.cnblogs.com/onlyac/p/5815566.html中有介绍 这次我们要探索注册slave请求和dump请求的报文格式和主要流程. 一.注 ...
- loadrunner录制脚本如何选择使用get请求和post请求的方式
在loadrunner工具里录制脚本时常常会用到get请求和post请求,有关loadrunner常用的这两类的请求主要有: get请求: web_url 和 web_link post请求: web ...
- iOS开发网络篇—GET请求和POST请求
iOS开发网络篇—GET请求和POST请求 一.GET请求和POST请求简单说明 创建GET请求 // 1.设置请求路径 NSString *urlStr=[NSString stringWithFo ...
- 普通请求和ajax请求的区别
普通请求和ajax请求的区别? 下面的action返回一个json文件,文件内容为sts.*,data1
- iOS开发网络篇—GET请求和POST请求(转)
一.GET请求和POST请求简单说明 创建GET请求 1 // 1.设置请求路径 2 NSString *urlStr=[NSString stringWithFormat:@"http:/ ...
- GET请求和POST请求的区别
request获取请求参数 最为常见的客户端传递参数方式有两种: 浏览器地址栏直接输入:一定是GET请求: 超链接:一定是GET请求: 表单:可以是GET,也可以是POST,这取决与<form& ...
- 使用SoapUI工具做get请求和post请求接口测试
祝大家节日快乐啦. 之前写过的一篇帖子已经介绍了SoapUI工具的基本使用,所以在此不再重复讲解关于建工程.建测试套件.添加用例等操作,可查看该篇文章详解:http://www.cnblogs.com ...
- Ajax相关——get请求和post请求的区别
一.完整的URL由以下几部分组成: scheme:通信协议,常用的有:http/ftp. host:主机,服务器(计算机)域名或IP地址 port:端口,整数,可选,省略时使用默认端口,http的默认 ...
随机推荐
- 七分钟理解 Java 的反射 API
像java一样,一种具有反射功能的语言.允许开发人员在运行时检查类型.方法.字段.注解等,并在程序运行时决定是否使用. 为此,Java的反射API提供类,类,字段,构造函数,方法,注释和其他. 使用它 ...
- JSON空值处理与 StringUtils工具类使用
JSON 动态查询时,需要的条件本应是null,前端传入的是" " //null转换为"" private static ValueFilter filter ...
- 小顶堆第二弹-----堆降序排序(C语言非递归)
现在po一下C语言版本的,留作以后接口使用. 1 #include <stdio.h> #include <stdlib.h> #define HEAP_SIZE 100 #d ...
- P1903 [国家集训队]数颜色 / 维护队列(带修莫队)
题目描述: 墨墨购买了一套N支彩色画笔(其中有些颜色可能相同),摆成一排,你需要回答墨墨的提问.墨墨会向你发布如下指令: 1. Q L R代表询问你从第L支画笔到第R支画笔中共有几种不同颜色的画笔. ...
- Java synchronized实现原理总结和偏量锁、轻量锁、重量锁、自旋锁
synchronized实现同步的基础:Java中的每一个对象都可以作为锁.具体表现为以下3种形式. 对于普通同步方法,锁是当前实例对象(this). 对于静态同步方法,锁是当前类的Class对象. ...
- DeferredResult使用方式和场景
为什么使用DeferredResult? API接口需要在指定时间内将异步操作的结果同步返回给前端时: Controller处理耗时任务,并且需要耗时任务的返回结果时: 当一个请求到达API接口,如果 ...
- 《发际线总是和我作对》第九次团队作业:【Beta】Scrum meeting1
项目 内容 这个作业属于哪个课程 软件工程 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目冲刺 团队名称 发际线总和我作队 作业学习目标 (1)掌握软件黑盒测试技术:(2)掌握软件 ...
- 解决SQL Error: 0, SQLState: S1009,Invalid value for getLong() - 'XX'的问题
内容简介 今天遇到一个异常,报出消息为SQL Error: 0, SQLState: S1009,Invalid value for getLong() - 'PH',排查问题后,结果令人哑然失笑,也 ...
- Windows下 Python 2 与 Python 3 共存
转自:http://lovenight.github.io/2016/09/27/Windows%E4%B8%8B-Python-2-%E4%B8%8E-Python-3-%E5%85%B1%E5%A ...
- Angular惰性加载的特性模块
一:Angular-CLI建立应用 cmd命令:ng new lazy-app --routing (创建一个名叫 lazy-app 的应用,而 --routing 标识生成了一个名叫 app- ...