博客
关于我
HttpLitener处理http请求和Websocket请求
阅读量:533 次
发布时间:2019-03-09

本文共 5405 字,大约阅读时间需要 18 分钟。

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;
}
}
}

 

转载地址:http://fmmiz.baihongyu.com/

你可能感兴趣的文章
Nginx配置负载均衡到后台网关集群
查看>>
ngrok | 内网穿透,支持 HTTPS、国内访问、静态域名
查看>>
NHibernate学习[1]
查看>>
NHibernate异常:No persister for的解决办法
查看>>
NIFI1.21.0_Mysql到Mysql增量CDC同步中_日期类型_以及null数据同步处理补充---大数据之Nifi工作笔记0057
查看>>
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表或全表增量同步_实现指定整库同步_或指定数据表同步配置_04---大数据之Nifi工作笔记0056
查看>>
NIFI1.23.2_最新版_性能优化通用_技巧积累_使用NIFI表达式过滤表_随时更新---大数据之Nifi工作笔记0063
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_根据binlog实现数据实时delete同步_实际操作04---大数据之Nifi工作笔记0043
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置binlog_使用处理器抓取binlog数据_实际操作01---大数据之Nifi工作笔记0040
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置数据路由_实现数据插入数据到目标数据库_实际操作03---大数据之Nifi工作笔记0042
查看>>
NIFI从MySql中离线读取数据再导入到MySql中_03_来吧用NIFI实现_数据分页获取功能---大数据之Nifi工作笔记0038
查看>>
NIFI从MySql中离线读取数据再导入到MySql中_无分页功能_02_转换数据_分割数据_提取JSON数据_替换拼接SQL_添加分页---大数据之Nifi工作笔记0037
查看>>
NIFI从PostGresql中离线读取数据再导入到MySql中_带有数据分页获取功能_不带分页不能用_NIFI资料太少了---大数据之Nifi工作笔记0039
查看>>
nifi使用过程-常见问题-以及入门总结---大数据之Nifi工作笔记0012
查看>>
NIFI分页获取Mysql数据_导入到Hbase中_并可通过phoenix客户端查询_含金量很高的一篇_搞了好久_实际操作05---大数据之Nifi工作笔记0045
查看>>
NIFI同步MySql数据_到SqlServer_错误_驱动程序无法通过使用安全套接字层(SSL)加密与SQL Server_Navicat连接SqlServer---大数据之Nifi工作笔记0047
查看>>
Nifi同步过程中报错create_time字段找不到_实际目标表和源表中没有这个字段---大数据之Nifi工作笔记0066
查看>>
NIFI大数据进阶_FlowFile拓扑_对FlowFile内容和属性的修改删除添加_介绍和描述_以及实际操作---大数据之Nifi工作笔记0023
查看>>