Spring WebSocket通过STOMP协议实现

3
我刚接触到websocket技术,并一直在探索Spring websocket解决方案。我已经按照以下链接中的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

1个回答

0

SockJS 的预期终端 URL 是一个 HTTP 终端。SockJS 会检查 WebSocket 协议是否可用,然后才会使用它或回退到其他选项,如长轮询。您的第一个选项是正确的:

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

STOMP客户端连接方法是非阻塞的,因此您需要提供一个回调函数,在连接建立后将被执行。您在调用连接方法后立即尝试通过该连接发送消息。连接还没有建立(太快了),因此您会收到错误消息:
Error: InvalidStateError: The connection has not been established yet

您需要将消息的发送移动到提供给connect方法的回调中,以确保它已经建立。订阅也是如此(在您的示例中已经这样做)。

还有一件事需要注意的是,STOMP目标不是URL。没有必要在目标前加上http://localhost:8080,目标应该只是/topic/greetings


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接