【发布时间】:2020-10-26 14:19:57
【问题描述】:
我正在尝试在我的 Web 应用程序中实现实时通知。只有我的网络应用中的管理员用户才能看到通知。
所以我在我的startup.cs文件which I think is not the right way中设置了网络套接字
Startup.cs
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
ReceiveBufferSize = 4 * 1024
};
app.UseWebSockets(webSocketOptions);
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
这是我的 Javascript
window.onload = () => {
if (/*User is Admin*/) {
//Establish Websocket
var socket = new WebSocket("wss:localhost:44301/ws");
console.log(socket.readyState);
socket.onerror = function (error) {
console.log('WebSocket Error: ' + error);
};
socket.onopen = function (event) {
console.log("Socket connection opened")
};
// Handle messages sent by the server.
socket.onmessage = function (event) {
var data = event.data;
console.log(data);
//Draw some beautiful HTML notification
};
}
}
现在一切正常,但我不知道如何从我的服务器控制器发送消息,类似这样
[HttpGet]
public async Task<IActionResult> Foo(WebSocket webSocket)
{
//What I am trying to do is send message from the open web socket connection.
var buffer = new byte[1024 * 4];
buffer = Encoding.UTF8.GetBytes("Foo");
await webSocket.SendAsync(new ArraySegment<byte>(buffer),WebSocketMessageType.Text,true,CancellationToken.None);
return View()
}
我不知道如何处理这个问题。我想做的是如果用户是管理员,打开 Web 套接字并从其他用户操作发送一些数据,(这意味着从我的一些控制器打开的 Web 套接字写入消息)
【问题讨论】:
-
我建议使用 SignalR 来处理此类问题。
标签: c# asp.net-core .net-core websocket