.NET Core 学习笔记之 WebSocketsSample
1. 服务端
代码如下:
Program:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; namespace WebSocketsServer
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
} public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
Startup:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace WebSocketsServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} // configure keep alive interval, receive buffer size
app.UseWebSockets(); app.Map("/samplesockets", app2 =>
{
// middleware to handle websocket request
app2.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
await SendMessagesAsync(context, webSocket, loggerFactory.CreateLogger("SendMessages"));
}
else
{
await next();
}
});
}); app.Run(async (context) =>
{
await context.Response.WriteAsync("Web Sockets sample");
});
} private async Task SendMessagesAsync(HttpContext context, WebSocket webSocket, ILogger logger)
{
var buffer = new byte[];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
if (result.MessageType == WebSocketMessageType.Text)
{
string content = Encoding.UTF8.GetString(buffer, , result.Count);
if (content.StartsWith("REQUESTMESSAGES:"))
{
string message = content.Substring("REQUESTMESSAGES:".Length);
for (int i = ; i < ; i++)
{
string messageToSend = $"{message} - {i}";
if (i == )
{
messageToSend += ";EOS"; // send end of sequence to not let the client wait for another message
}
byte[] sendBuffer = Encoding.UTF8.GetBytes(messageToSend);
await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
logger.LogDebug("sent message {0}", messageToSend);
await Task.Delay();
}
} if (content.Equals("SERVERCLOSE"))
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye for now", CancellationToken.None);
logger.LogDebug("client sent close request, socket closing");
return;
}
else if (content.Equals("SERVERABORT"))
{
context.Abort();
}
} result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
}
}
}
}
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58167/",
"sslPort":
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebSocketsServer": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:58168/"
}
}
}
2. 客户端
Program.cs
代码如下:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace WebSocketClient
{
class Program
{
static async Task Main()
{
Console.WriteLine("Client - wait for server");
Console.ReadLine();
await InitiateWebSocketCommunication("ws://localhost:58167/samplesockets");
//"ws://localhost:6295/samplesockets"
//http://localhost:58167/
Console.WriteLine("Program end");
Console.ReadLine();
} static async Task InitiateWebSocketCommunication(string address)
{
try
{
var webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(address), CancellationToken.None); await SendAndReceiveAsync(webSocket, "A");
await SendAndReceiveAsync(webSocket, "B");
await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("SERVERCLOSE")),
WebSocketMessageType.Text,
endOfMessage: true,
CancellationToken.None);
var buffer = new byte[];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None); Console.WriteLine($"received for close: " +
$"{result.CloseStatus} " +
$"{result.CloseStatusDescription} " +
$"{Encoding.UTF8.GetString(buffer, 0, result.Count)}");
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
"Bye",
CancellationToken.None); }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} static async Task SendAndReceiveAsync(WebSocket webSocket, string term)
{
byte[] data = Encoding.UTF8.GetBytes($"REQUESTMESSAGES:{term}");
var buffer = new byte[]; await webSocket.SendAsync(new ArraySegment<byte>(data),
WebSocketMessageType.Text,
endOfMessage: true,
CancellationToken.None);
WebSocketReceiveResult result;
bool sequenceEnd = false;
do
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),
CancellationToken.None);
string dataReceived = Encoding.UTF8.GetString(buffer, , result.Count);
Console.WriteLine($"received {dataReceived}");
if (dataReceived.Contains("EOS"))
{
sequenceEnd = true;
} } while (!(result?.CloseStatus.HasValue ?? false) && !sequenceEnd);
}
}
}
运行截图

谢谢浏览!
.NET Core 学习笔记之 WebSocketsSample的更多相关文章
- .NET CORE学习笔记系列(2)——依赖注入[7]: .NET Core DI框架[服务注册]
原文https://www.cnblogs.com/artech/p/net-core-di-07.html 包含服务注册信息的IServiceCollection对象最终被用来创建作为DI容器的IS ...
- .NET CORE学习笔记系列(2)——依赖注入[6]: .NET Core DI框架[编程体验]
原文https://www.cnblogs.com/artech/p/net-core-di-06.html 毫不夸张地说,整个ASP.NET Core框架是建立在一个依赖注入框架之上的,它在应用启动 ...
- .NET CORE学习笔记系列(2)——依赖注入[5]: 创建一个简易版的DI框架[下篇]
为了让读者朋友们能够对.NET Core DI框架的实现原理具有一个深刻而认识,我们采用与之类似的设计构架了一个名为Cat的DI框架.在上篇中我们介绍了Cat的基本编程模式,接下来我们就来聊聊Cat的 ...
- .NET CORE学习笔记系列(2)——依赖注入[4]: 创建一个简易版的DI框架[上篇]
原文https://www.cnblogs.com/artech/p/net-core-di-04.html 本系列文章旨在剖析.NET Core的依赖注入框架的实现原理,到目前为止我们通过三篇文章从 ...
- .NET CORE学习笔记系列(2)——依赖注入【3】依赖注入模式
原文:https://www.cnblogs.com/artech/p/net-core-di-03.html IoC主要体现了这样一种设计思想:通过将一组通用流程的控制权从应用转移到框架中以实现对流 ...
- .NET CORE学习笔记系列(2)——依赖注入【2】基于IoC的设计模式
原文:https://www.cnblogs.com/artech/p/net-core-di-02.html 正如我们在<控制反转>提到过的,很多人将IoC理解为一种“面向对象的设计模式 ...
- .NET CORE学习笔记系列(2)——依赖注入【1】控制反转IOC
原文:https://www.cnblogs.com/artech/p/net-core-di-01.html 一.流程控制的反转 IoC的全名Inverse of Control,翻译成中文就是“控 ...
- .NET Core学习笔记(7)——Exception最佳实践
1.为什么不要给每个方法都写try catch 为每个方法都编写try catch是错误的做法,理由如下: a.重复嵌套的try catch是无用的,多余的. 这一点非常容易理解,下面的示例代码中,O ...
- .net core学习笔记,组件篇:服务的注册与发现(Consul)初篇
1.什么是服务注册中心? 在学习服务注册与发现时,我们要先搞明白到底什么是服务注册与发现. 在这里我举一个生活中非常普遍的例子——网购来简单说明,网购在我们日常生活中已经是非常普遍了,其实网购中的(商 ...
随机推荐
- Linux - 几种方法来实现scp拷贝时无需输入密码
前言 在实际工作中,经常会将本地的一些文件传送到远程的机器上.scp是一个很好用的命令,缺点是需要手工输入密码. 如何在shell脚本中实现传输文件,而不用手工输入密码呢?接下来介绍三种方法. 一.建 ...
- .net core 的 aop 实现方法汇总
decorator 不借助第三方DI容器,通过装饰模式通过内置的DI容器实现 https://medium.com/@willie.tetlow/net-core-dependency-injecti ...
- Jenkins 有关 Maven 的内容
Jenkins Maven 插件安装 在安装完 Jenkins 后,我们想添加新的项目 为 Maven 项目时,发现找不到这个选项. 原因是我们没有安装插件 Maven Integration. 在 ...
- RabbitMQ的消息确认ACK机制
1.什么是消息确认ACK. 答:如果在处理消息的过程中,消费者的服务器在处理消息的时候出现异常,那么可能这条正在处理的消息就没有完成消息消费,数据就会丢失.为了确保数据不会丢失,RabbitMQ支持消 ...
- Koa 中间件的执行
Node.js 中请求的处理 讨论 Koa 中间件前,先看原生 Node.js 中是如何创建 server 和处理请求的. node_server.js const http = require(&q ...
- SpringBoot(14)—注解装配Bean
SpringBoot(14)-注解装配Bean SpringBoot装配Bean方式主要有两种 通过Java配置文件@Bean的方式定义Bean. 通过注解扫描的方式@Component/@Compo ...
- AspNet Katana中Authentication有关的业务逻辑
我将从CookieAuthenticationMiddleware中间件的使用,来讲述cookie认证是如何实现的 1.系统是如何调用CookieAuthenticationMiddleware的 在 ...
- Python 容器使用的 5 个技巧和 2 个误区
"容器"这两个字很少被 Python 技术文章提起.一看到"容器",大家想到的多是那头蓝色小鲸鱼:Docker,但这篇文章和它没有任何关系.本文里的容器,是 P ...
- mybatis关联关系映射
1.一对多关联关系 2.多对多关联关系 首先先用逆向生成工具生成t_hibernate_order.t_hibernate_order_item t_hibernate_book.t_hibernat ...
- Windows下的DNS命令用法
- ipconfig 查看DNS缓存内容: ipconfig /displaydns 将显示所有缓存的DNS解析结果. 清空DNS缓存内容: ipconfig /flushdns 将清空缓存的DNS解 ...