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

}
}

原文地址:https://www.cnblogs.com/1175429393wljblog/p/11277189.html

时间: 2024-08-30 14:03:32

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

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

iOS开发网络篇—GET请求和POST请求 一.GET请求和POST请求简单说明 创建GET请求 1 // 1.设置请求路径 2 NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text]; 3 NSURL *url=[NSURL URLWithString:u

HttpClient之Get请求和Post请求示例 编辑

HttpClient的撑持在HTTP/1.1标准中界说的一切的HTTP办法:GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS.每有一个办法都有一个对应的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions.一切的这些类均完成了HttpUriRequest接口,故可以作为execute的履行参数使用.恳求URI是可以使用恳求的一致资本标识符. HTTP恳求的URI包括一个协

GET请求和POST请求区别

GET请求和POST请求区别 1.GET被强制服务器支持 GET通常用于请求服务器发送某个资源.在HTTP/1.1中,要求服务器实现此方法;POST请求方法起初是用来向服务器输入数据的.在HTTP/1.1中,POST方法是可选被实现的,没有明确规定要求服务器实现. 2.浏览器对URL的长度有限制,所以GET请求不能代替POST请求发送大量数据 RFC 2616 中明确对 uri 的长度并没有限制.不过虽然在RFC中并没有对uri的长度进行限制,但是各大浏览器厂家在实现的时候限制了URL的长度,可

HttpClient之Get请求和Post请求示例

HttpClient之Get请求和Post请求示例 博客分类: Java综合 HttpClient的支持在HTTP/1.1规范中定义的所有的HTTP方法:GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS.每有一个方法都有一个对应的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions.所有的这些类均实现了HttpUriRequest接口,故可以作为execute的执行参数使

httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求

1.httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求. http 连接一次就有返回流.http是个双向的嘛.只有连接了,就会有输出返回流. 所以在执行http连接的时候,返回值都是http连接的返回流. HttpResponse response = client.execute(httpPost); 2.http发送,body里是可以写入中文的.但要注意乱码问题: public static String getHttpRequestString(Str

普通请求和ajax请求的区别

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

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

一.GET请求和POST请求简单说明 创建GET请求 1 // 1.设置请求路径 2 NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text]; 3 NSURL *url=[NSURL URLWithString:urlStr]; 4 5 // 2.创建请求对

iOS 在线模拟post请求和get请求

一般做app的接口一般都是post和get请求.如果是get请求的话.直接可以在网址访问,post请求的就不可以.这个时候就需要处理.今天尝试了一下这个.http://www.atool.org/httptest.php这个网站可以模拟post请求和get请求.以后写代码就更快捷了

浏览器的get请求和post请求的区别

GET 请求和 POST 请求: 1). 使用GET方式传递参数: ①. 在浏览器地址栏中输入某个URL地址或单击网页上的一个超链接时,浏览器发出的HTTP请求消息的请求方式为              GET. 例如:  http://localhost:8080/20161106-JavaWeb-Servlet/index.html 或<a href="input.html"></a>②. 如果网页中的<form>表单元素的 method 属性明