博客
关于我
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/

你可能感兴趣的文章
Mysql学习总结(71)——数据库介绍(MySQL安装 体系结构、基本管理)再回顾
查看>>
Mysql学习总结(72)——MySQL 开发者开发,设计规范再总结
查看>>
Mysql学习总结(73)——MySQL 查询A表存在B表不存在的数据SQL总结
查看>>
Mysql学习总结(74)——慢SQL!压垮团队的最后一根稻草!
查看>>
Mysql学习总结(75)——并发量大、数据量大的互联网业务数据库设计军规
查看>>
Mysql学习总结(76)——MySQL执行计划(explain)结果含义总结
查看>>
Mysql学习总结(77)——温故Mysql数据库开发核心原则与规范
查看>>
Mysql学习总结(78)——MySQL各版本差异整理
查看>>
Mysql学习总结(79)——MySQL常用函数总结
查看>>
Mysql学习总结(7)——MySql索引原理与使用大全
查看>>
Mysql学习总结(80)——统计数据库的总记录数和库中各个表的数据量
查看>>
Mysql学习总结(81)——为什么MySQL不推荐使用uuid或者雪花id作为主键?
查看>>
Mysql学习总结(82)——MySQL逻辑删除与数据库唯一性约束如何解决?
查看>>
Mysql学习总结(83)——常用的几种分布式锁:ZK分布式锁、Redis分布式锁、数据库分布式锁、基于JDK的分布式锁方案对比总结
查看>>
Mysql学习总结(84)—— Mysql的主从复制延迟问题总结
查看>>
Mysql学习总结(85)——开发人员最应该明白的数据库设计原则
查看>>
Mysql学习总结(8)——MySql基本查询、连接查询、子查询、正则表达查询讲解
查看>>
Mysql学习总结(9)——MySql视图原理讲解与使用大全
查看>>
Mysql学习笔记 - 在Centos7环境下离线安装Mysql
查看>>
MySQL学习笔记十七:复制特性
查看>>