jquery 无法使用标准连接到wss,js,但它的工作方式是signalr脚本

kb5ga3dv  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(123)

我做了一个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>

我做错了什么??

lskq00tm

lskq00tm1#

您需要包含SignalR库:

<script src="Scripts/jquery.signalR-2.4.3.min.js"></script>

然后,将$.get()替换为$.ajax()

async function getNegotiationDetails() {
  let URL = 'https://localhost:44399/signalr/ChatHub/negotiate?clientProtocol=1.5';
  let negotiations = await $.ajax({
    url: URL,
    method: 'GET'
  });
  let token = encodeURIComponent(negotiations.ConnectionToken);
  return Promise.resolve(token);
}

getNegotiationDetails().then((token) => {
  console.log(token);
  // Rest of the WebSocket connection code
});

最后,在wssPath变量中,在clientProtocol查询参数之前有一个额外的空间。删除该空格以确保URL格式正确。

let wssPath = "wss://localhost:44399/signalr/ChatHub?clientProtocol=1.5&transport=webSockets&connectionToken=" + token;

保持联系

相关问题