我尝试实现一种将客户端连接到 signalR 集线器的方法。 我不能只采用 SignalR 库,因为我想将其添加到使用 rollup 构建的库中(并且它不是使用 rollup 构建的)
对于测试,我有一个线程每 10 秒向所有客户端发送一条消息:
Thread cyclicThread = ThreadUtils.GetCyclicThread(10000, () =>
{
this.NotificationHub.Clients.All.SendAsync("methodeTestBis", 239);
});
cyclicThread.Start();
使用 signalR 库,它可以工作,我可以在 Chrome 调试器的网络选项卡中看到消息。
// Tests with signalR js library, messages receiving
const connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start();
但是当我使用 WebSocket 处理来自 signalR hub 的消息时,它不起作用。 onopen 函数被触发,但 onmessage 函数没有被触发,并且我在网络选项卡中没有看到此 WebSocket 的消息。
// Tests with WebSocket, messages not receiving
let url = "https://localhost:7143/chatHub";
const headers = {};
const [name, value] = getUserAgentHeader();
headers[name] = value;
fetch(`${url}/negotiate?negotiateVersion=1`, {
method: "POST",
headers: {
"Content-Type": "application/json",
headers,
},
body: JSON.stringify({
content: "",
headers: headers,
timeout: 100000,
withCredentials: true,
}),
}).then((response) => response.json())
.then((response) => {
// The fetch return here some information about signalR connection, and the token for idendification
console.log(response);
// The web socket for SignalR's connection
const wsUrl = `${url}?id=${response.connectionToken}`.replace(/^http/, "ws");
const webSocket = new WebSocket(wsUrl);
webSocket.onopen = (event) => {
// It's triggered
console.log(event);
}
webSocket.onmessage = (message) => {
// It's not triggered
console.log(message);
}
webSocket.onerror = (event) => {
console.log(event);
console.log(event.error);
}
webSocket.onclose = (event) => {
console.log(event);
}
});
// The next two functions is from signalR, used for tests and debug what's wrong
function getUserAgentHeader() {
let userAgentHeaderName = "X-SignalR-User-Agent";
return [userAgentHeaderName, constructUserAgent("7.0.5", undefined, "Browser", undefined)];
}
function constructUserAgent(version, os, runtime, runtimeVersion) {
// Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])
let userAgent = "Microsoft SignalR/";
const majorAndMinor = version.split(".");
userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;
userAgent += ` (${version}; `;
if (os && os !== "") {
userAgent += `${os}; `;
}
else {
userAgent += "Unknown OS; ";
}
userAgent += `${runtime}`;
if (runtimeVersion) {
userAgent += `; ${runtimeVersion}`;
}
else {
userAgent += "; Unknown Runtime Version";
}
userAgent += ")";
return userAgent;
}
有人知道我做错了什么吗?
有获取 signalR 库的链接: https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js
我用来制作自己的WebSocket代码的代码位于第2251行和2342行之间
我找到了另一种方法来解决我的问题。
以前,在我的 React 库中,我使用下一行导入 signalR :
import signalR, { HubConnection } from "@microsoft/signalr";
现在,我使用以下导入,它可以与我的库中的 npm run rollup 一起使用:
import * as signalR from "@microsoft/signalr";
而且我没有错误“@microsoft/signalr 未导出默认值”