3

我是 websocket 的新手,一直在探索 spring websocket 解决方案,我已经从以下 url 实现了 hello world 应用程序:Spring websocket

我想从 nodejs 调用服务器,而不是使用 index.html 页面。这是我使用 SockJS 和 Stompjs 的实现。

var url = 'http://localhost:8080'

var SockJS = require('sockjs-client'),
    Stomp  = require('stompjs'),
    socket = new SockJS(url + '/hello'),

    client = Stomp.over(socket)

function connect(){
  client.connect({}, function(frame){
    console.log(frame)
    client.subscribe(url + '/topic/greetings', function(greeting){
      console.log(greeting)
    })
  })
}

function sendName(){
  var name = 'Gideon'
  client.send(url + '/app/hello', {}, JSON.stringify({ 'name': name }))
}

function disconnect(){
  if(client)
    client.disconnect()
}

function start(){
  connect()
  sendName()
}

start();

我运行脚本node --harmony index.js

这是我在尝试不同的 url 时遇到的错误:

url :var socket = new SockJS('http://localhost:8080/hello')
Error: InvalidStateError: The connection has not been established yet

url: var socket = new SockJS('/hello')
Error: The URL '/hello' is invalid

url: var socket = new SockJS('ws://localhost:8080/hello')  
Error: The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.

我的依赖

"dependencies": {
   "sockjs-client": "^1.0.3",
   "stompjs": "^2.3.3"
 }

项目可以在这里找到:https ://bitbucket.org/gideon_o/spring-websocket-test

4

1 回答 1

0

SockJS 的预期端点 URL 是 HTTP 端点。SockJS 将在使用 WebSocket 协议之前检查它是否可用,或者回退到其他选项,如长轮询。您的第一个选项是正确的:

var socket = new SockJS('http://localhost:8080/hello')

STOMP 客户端连接方法是非阻塞的,这就是为什么您提供一个回调,该回调将在连接建立时执行。您正在尝试在调用 connect 方法后立即通过该连接发送消息。连接尚未建立(太快),您会收到错误消息:

Error: InvalidStateError: The connection has not been established yet

您必须将消息的发送移动到提供给 connect 方法的回调,以确保它已经建立。这同样适用于订阅(您在示例中已经这样做了)。

还有一点需要注意的是,STOMP 目标不是 URL。不需要在目的地前面加上http://localhost:8080,目的地应该很简单/topic/greetings

于 2018-04-09T15:08:38.863 回答