我正在try 与我的react应用程序建立信号器连接,我已经在asp中创建了中心.net核心,但它似乎不会在我的前端工作.
说到信号器,我是新手,但我以前用asp.net核心的MVC应用程序,所以我知道它的逻辑工作.
但我从来没有用React处理过信号器.这就是我需要帮助的原因.
让我给你看一些代码
public class OnConnectionHub : Hub
{
public static int ConnectionCount { get; set; }
public override Task OnConnectedAsync()
{
ConnectionCount++;
Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception? exception)
{
ConnectionCount--;
Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
return base.OnDisconnectedAsync(exception);
}
}
相当简单,只需在OnConnectedAsync
和OnDisconnectedAsync
上递增和递减
这是我创建的中心url
endpoints.MapHub<OnConnectionHub>("hubs/onConnectionHub");
这是我的react组件中的一些代码
import { HubConnectionBuilder } from "@microsoft/signalr"
import { useState } from "react"
export const ConnectionCount = () => {
const [connectionCount, setConnectionCount] = useState(0)
// create connection
const connection = new HubConnectionBuilder()
.withUrl("https://localhost:7199/hubs/onConnectionHub")
.build()
// connect to method that hub invokes
connection.on("updateConnectionCount", (onConnection) => {
setConnectionCount(onConnection)
}
)
// start connection
connection.start();
return <p>Active members {connectionCount}</p>
}
我得到的错误
react_devtools_backend.js:4026 [2022-07-14T08:31:46.444Z] Error: Failed to complete negotiation with the server: TypeError: Failed to fetch
client.onmessage @ WebSocketClient.js:50
2HttpConnection.ts:350 Uncaught (in promise) Error: Failed to complete negotiation with the server: TypeError: Failed to fetch
at HttpConnection._getNegotiationResponse (HttpConnection.ts:350:1)
at async HttpConnection._startInternal (HttpConnection.ts:247:1)
at async HttpConnection.start (HttpConnection.ts:138:1)
at async HubConnection._startInternal (HubConnection.ts:206:1)
at async HubConnection._startWithStateTransitions (HubConnection.ts:180:1)
谢谢