.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.什么是服务注册中心? 在学习服务注册与发现时,我们要先搞明白到底什么是服务注册与发现. 在这里我举一个生活中非常普遍的例子——网购来简单说明,网购在我们日常生活中已经是非常普遍了,其实网购中的(商 ...
随机推荐
- 什么是SFP光模块?
什么是光模块? 光模块(optical module)由光电子器件.功能电路和光接口等组成,光电子器件包括发射和接收两部分.简单的说,光模块的作用就是光电转换,发送端把电信号转换成光信号,通过光纤传送 ...
- [反汇编]函数开始部分利用mov ebx,esp找到返回地址(_KTRAP_FRAME结构)
我们理解call原理,首先将返回地址压入栈中,之后执行调用. 因此,在一个函数开始部分,esp依旧是上一个栈帧的esp,此时esp指向返回地址. 这就意味着使用 mov ebx,esp,之后 [ebx ...
- 机器学习实战:基于Scikit-Learn和TensorFlow 读书笔记 第6章 决策树
数据挖掘作业,要实现决策树,现记录学习过程 win10系统,Python 3.7.0 构建一个决策树,在鸢尾花数据集上训练一个DecisionTreeClassifier: from sklearn. ...
- 并发—JVM内部机制和外部机制处理方法
并发常见的编程场景,一句话概括就是,需要协调多个线程之间的协作,已保证程序按照自己原本的意愿执行.那么究竟应该如何协调多个线程? 这个问题比较宽泛,一般情况下,我们按照方式的纬度去简单区分,有以下两种 ...
- crm-1
1.crm 客户关系管理系统 :1.业务逻辑部分 2.权限插件 2.forms组件之modelform modelform就是model+form ,form根据model的字段生成标签 ,校验信息 ...
- XHR 对象实例所有的配置、属性、方法、回调和不可变值
当我们声明了一个XMLHttpRequest对象的实例的时候,使用for-in来循环遍历一下这个实例(本文使用的是chrome45版本浏览器),我们会发现在这个实例上绑定了一些内容,我把这些内容进行了 ...
- SQLi-LABS Page-3 (Stacked injections) Less-38-Less-45
Less-38 堆叠注入原理简介堆叠注入简介 Stacked injections: 堆叠注入.从名词的含义就可以看到应该是一堆 sql 语句(多条)一起执行.而在真实的运用中也是这样的, 我们知道在 ...
- Android TextView文本处理库推荐
版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/115 Android TextView文本处理库推荐 现在 ...
- 源码包安装转换rpm包
目录 纯净版虚拟机 1. 先安装个虚拟机,登陆nginx官网 http://nginx.org/选择一个稳定的版本 2. 右键复制地址,到新克隆的纯净虚拟机wget 下载 3.源码包 4.解压 tar ...
- [20190520]exp imp on th fly.txt
[20190520]exp imp on th fly.txt --//以前做的测试,查找浪费许多时间,做1个记录.--//注:仅仅linux 操作系统,bash shell版本不能太低就可以实现,现 ...