gpt4 book ai didi

javascript - 无法从 javascript 连接到 ASP.NET Core websocket

转载 作者:行者123 更新时间:2023-12-02 23:41:49 24 4
gpt4 key购买 nike

我从 https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/websockets/samples/2.x/WebSocketsSample 的示例应用程序创建了一个简单的 ASP.NET websocket 服务器。

在提供的 Razor 页面上效果很好...

enter image description here这是接受套接字连接的服务器代码的一部分。

        app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}

});

但现在使用改编自 https://www.websocket.org/echo.html 的代码它严重失败...

enter image description here

这是改编后的代码的一部分...

//  var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://localhost:36472/ws"
var output;

function init()
{
output = document.getElementById("output");
testWebSocket();
}

function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}

这是预期的行为吗?!难道javascript和ASP.NET Core就没有办法通过websockets进行互操作了吗?!

最佳答案

我尝试复制您的问题,但似乎运行良好。

我启动了一个新的 .NET Core 项目,并添加了您提到的 WebSocketsSample 中的代码:

Startup.cs

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApplication3
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
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();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}

});

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseStaticFiles();
app.UseMvc();
}

private async Task Echo(HttpContext context, WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
}

Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace WebApplication3
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

在 UI 端,我创建了一个空页面并粘贴了您提供的 JS 代码:

Index.cshtml

@page
@model IndexModel
@{
ViewData["Title"] = "";
}

<div id="output"></div>

@section Scripts{
<script language="javascript" type="text/javascript">

//var wsUri = "wss://echo.websocket.org/";
var wsUri = "wss://localhost:44357/ws";
var output;

function init() {
output = document.getElementById("output");
testWebSocket();
}

function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function (evt) { onClose(evt) };
websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}

function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}

function onClose(evt) {
writeToScreen("DISCONNECTED");
}

function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
websocket.close();
}

function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}

function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}

window.addEventListener("load", init, false);

</script>
}

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebApplication</title>
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("Scripts", required: false)
</body>
</html>

这是我得到的结果:

enter image description here

以防万一,这里有一个 zip 存档,代码为:https://ufile.io/pm2ljcbn

所以你的代码应该没问题。我错过了什么吗?

关于javascript - 无法从 javascript 连接到 ASP.NET Core websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56032158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com