3

Im new to websocket and have been exploring spring websocket solution, I've implemented the hello world application from the following url: Spring websocket.

Instead of using the index.html page, I would like to call the server from nodejs. Here is my implementation with SockJS and 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();

I run the script with node --harmony index.js

This are the errors i'm getting when trying different 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.

My dependencies

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

Project can be found here: https://bitbucket.org/gideon_o/spring-websocket-test

Gideon Oduro
  • 200
  • 1
  • 2
  • 15

1 Answers1

0

The expected endpoint URL for SockJS is an HTTP endpoint. SockJS will check if the WebSocket protocol is available before using it or falling back to other options like long polling. Your first option is the correct one:

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

The STOMP client connect method is non-blocking, that's why you provide a callback that will be executed when the connection is stablished. You are trying to send a message over that connection right after calling the connect method. The connection hasn't been stablished yet (too fast), and you get the error message:

Error: InvalidStateError: The connection has not been established yet

You'll have to move the sending of the message to the callback provided to the connect method to make sure it is already stablished. The same applies to subscriptions (which you already do in your example).

One more thing to notice is that a STOMP destination is not a URL. There's no need to prefix the destination with http://localhost:8080, the destination should be simply /topic/greetings

Sergi Almar
  • 8,054
  • 3
  • 32
  • 30