如何在ASP.NET Core中使用WebSockets [英] How to use websockets in asp.net core

查看:93
本文介绍了如何在ASP.NET Core中使用WebSockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开发一款游戏,在其中我将记分牌存储在存储在服务器(当前在本地主机)上的文本文件中.我正在使用http get和post调用,以便与服务器通信并获取和发送所需的数据.现在,我想实现websocket以便从服务器向c#客户端发送通知.该通知将仅在控制台上为用户显示一条消息,例如,在每当将用户添加到记分板上,每次调用UpdateScoreBoard方法时,我想向用户显示一条消息.根据我在网上找到的教程,我设法构建了以下代码,有人可以让我更清楚地知道我将如何为服务器构建Websocket,以及如何在客户端上初始化Websocket?谢谢

Startup.cs(服务器)

  public void配置(IApplicationBuilder应用程序,IHostEnvironment env){//已删除的代码var webSocketOptions = new WebSocketOptions(){KeepAliveInterval = TimeSpan.FromSeconds(120),ReceiveBufferSize = 4 * 1024};app.UseWebSockets(webSocketOptions);app.Use(async(context,next)=>{如果(context.Request.Path =="/ws"){如果(context.WebSockets.IsWebSocketRequest){WebSocket webSocket =等待context.WebSockets.AcceptWebSocketAsync();等待Echo(context,webSocket);}别的{context.Response.StatusCode = 400;}}别的{等待next();}});}私有异步任务Echo(HttpContext context,WebSocket webSocket){var buffer = new byte [1024 * 4];WebSocketReceiveResult结果=等待webSocket.ReceiveAsync(new ArraySegment< byte>(buffer),CancellationToken.None);while(!result.CloseStatus.HasValue){等待webSocket.SendAsync(new ArraySegment< byte>(缓冲区,0,result.Count),result.MessageType,result.EndOfMessage,CancellationToken.None);结果=等待webSocket.ReceiveAsync(new ArraySegment< byte>(buffer),CancellationToken.None);}等待webSocket.CloseAsync(result.CloseStatus.Value,result.CloseStatusDescription,CancellationToken.None);} 

HttpClass.cs(客户端)-我在其中调用http发布请求

 公共异步覆盖任务< List< Scoreboard>>UpdateScoreBoards(字符串用户名,整数尝试,整数秒,DateTime日期){HttpResponseMessage response = null;//创建对象记分板的新实例//已删除的代码var url ="http://localhost:5000/api/Scoreboard";var socket_url = new Uri("ws://localhost:5000");var exitEvent = new ManualResetEvent(false);使用(var client = new WebsocketClient(socket_url)){client.ReconnectTimeout = TimeSpan.FromSeconds(30);client.ReconnectionHappened.Subscribe(info =>Log.Information($发生重新连接,键入:{info.Type}")));client.MessageReceived.Subscribe(msg => Log.Information($收到的消息:{msg}")));等待client.Start();等待Task.Run(()=> client.Send("test")));exitEvent.WaitOne();}//删除的代码} 

解决方案

任何人都可以让我更清楚地知道我将如何为服务器构建Websocket,以及如何在客户端上初始化Websocket?

如您所引用的示例所示,在ASP.NET Core中使用WebSocket,我们可以添加

此外,ASP.NET Core SignalR是一个开放源代码库,可简化实现实时通信功能的过程.而且它确实支持WebSockets传输,我们可以轻松地向所有连接的客户端或连接的客户端的指定子集实现推送消息/通知.

有关ASP.NET Core SignalR的更多信息,可以查看以下文档: 解决方案

can anyone make it more clear for me how the i will build the websocket for the server and how i will initialize the websocket on the client?

As the example that you referenced demonstrated, making use of WebSocket in ASP.NET Core, we can add the WebSockets middleware in the Configure method, then add/configure request delegate to check and handle incoming WebSocket requests.

And after transitioned a request to a WebSocket connection with AcceptWebSocketAsync() method, we can use the returned WebSocket object to send and receive messages.

In Echo method, we can also perform custom code logic to generate and send reply message/notification based on received message(s).

//received message
var mes = Encoding.UTF8.GetString(buffer, 0, result.Count);

//code logic here
//...

//create reply message
var reply_mes = $"You sent {mes}.";

byte[] reply_mes_buffer = Encoding.UTF8.GetBytes(reply_mes);

await webSocket.SendAsync(new ArraySegment<byte>(reply_mes_buffer, 0, reply_mes.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);

Besides, ASP.NET Core SignalR is an open-source library that simplifies implementing real-time communication functionality. And it does support WebSockets transport and we can easily achieving push messages/notifications to all connected clients or specified subsets of connected clients.

For more information about ASP.NET Core SignalR, you can check this doc: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1

这篇关于如何在ASP.NET Core中使用WebSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆