我做了一个signalR服务器应用程序。简单的wss服务器。如果我通过signalR.js调用它,我工作得很好。但是如果我尝试通过std.js和Postman wss插件调用它,我会得到一个到xxxxx的WebSocket连接失败。而且我必须从非浏览器客户端调用它。我得到令牌ok回来:
{"Url":"/signalr/ChatHub","ConnectionToken":"AcOXMhpMcYlqJnPrE5QShYeCuODNI7Abv2c9utk5EJhGGVFxoSsFhj5WqJgk7IM2FqyvQ7oBcp03dGUSv+7ux6QeW+uaaV3NKqCDY53wOaNboI1pihJwIRy2CrQo3pm0","ConnectionId":"32720752-aa1d-4024-89b1-50297a76c39f","KeepAliveTimeout":20.0,"DisconnectTimeout":30.0,"ConnectionTimeout":110.0,"TryWebSockets":true,"ProtocolVersion":"1.5","TransportConnectTimeout":5.0,"LongPollDelay":0.0}
有效脚本:
<script src="Scripts/jquery-3.7.0.min.js" ></script>
<script src="Scripts/jquery.signalR-2.4.3.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (Data) {
$('#discussion').append('<li><strong>' + Data + '</strong></li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
chat.server.send('@JsonValue');
});
});
发送的脚本:
<script src="Scripts/jquery-3.7.0.min.js" ></script>
<script type="text/javascript">
async function f() {
let URL = 'https://localhost:44399/signalr/ChatHub/negotiate?clientProtocol=1.5';
let negotiations = await $.get(URL);
let token = encodeURIComponent(negotiations.ConnectionToken);
return Promise.resolve(token)
}
f().then((token) => {
console.log(token)
let wssPath = "wss://localhost:44399/signalr/ChatHub? clientProtocol=1.5&transport=webSockets&connectionToken=" + token
try {
let ws = new WebSocket(wssPath);
}
catch (e) {
alert(e)
}
});
</script>
我做错了什么??
1条答案
按热度按时间lskq00tm1#
您需要包含
SignalR
库:然后,将
$.get()
替换为$.ajax()
:最后,在
wssPath
变量中,在clientProtocol
查询参数之前有一个额外的空间。删除该空格以确保URL格式正确。保持联系