Giter Site home page Giter Site logo

jmesnil / stomp-websocket Goto Github PK

View Code? Open in Web Editor NEW
1.4K 69.0 588.0 1.78 MB

Stomp client for Web browsers and node.js apps

Home Page: http://jmesnil.net/stomp-websocket/doc/

License: Apache License 2.0

CoffeeScript 32.26% JavaScript 51.43% CSS 3.17% HTML 13.15%

stomp-websocket's Introduction

STOMP.js

This library provides a STOMP client for Web browser (using Web Sockets) or node.js applications (either using raw TCP sockets or Web Sockets).

Project Status

This project is no longer maintained (some context about this decision).

If you encounter bugs with it or need enhancements, you can fork it and modify it as the project is under the Apache License 2.0.

Web Browser support

The library file is located in lib/stomp.js (a minified version is available in lib/stomp.min.js). It does not require any dependency (except WebSocket support from the browser or an alternative to WebSocket!)

Online documentation describes the library API (including the annotated source code).

node.js support

Install the 'stompjs' module

$ npm install stompjs

In the node.js app, require the module with:

var Stomp = require('stompjs');

To connect to a STOMP broker over a TCP socket, use the Stomp.overTCP(host, port) method:

var client = Stomp.overTCP('localhost', 61613);

To connect to a STOMP broker over a WebSocket, use instead the Stomp.overWS(url) method:

var client = Stomp.overWS('ws://localhost:61614');

Development Requirements

For development (testing, building) the project requires node.js. This allows us to run tests without the browser continuously during development (see cake watch).

$ npm install

Building and Testing

Build Status

To build JavaScript from the CoffeeScript source code:

$ cake build

To run tests:

$ cake test

To continuously run tests on file changes:

$ cake watch

Browser Tests

  • Make sure you have a running STOMP broker which supports the WebSocket protocol (see the documentation)
  • Open in your web browser the project's test page
  • Check all tests pass

Use

The project contains examples for using stomp.js to send and receive STOMP messages from a server directly in the Web Browser or in a WebWorker.

Authors

stomp-websocket's People

Contributors

ceefour avatar chirino avatar dejanb avatar iuridiniz avatar jmesnil avatar matzew avatar mgjbroadbent avatar progrium avatar shanti2530 avatar si14 avatar wemrysi avatar williamsbdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stomp-websocket's Issues

implicit subscription support

The documentation says: "To receive messages in the browser, the STOMP client must first subscribe to a destination." Is there a way of receiving messages that arrive without such an explicit subscription?

The RabbitMQ STOMP adapter can create implicit subscriptions when temporary destinations are used. ("Temp Queue Destinations" in http://www.rabbitmq.com/stomp.html)

Demo doesn't work with ActiveMQ 5.5

Tried it and get "Opening Web Socket...
Whoops! Lost connection to undefined"

ActiveMQ Config:
transportConnector name="websocket" uri="ws://0.0.0.0:61614"

telnet localhost 614614 works.

Stomp config- Server URL: ws://localhost:61614/stomp

Serving demo from a Grails (Tomcat) server on localhost:8080

"ReferenceError: error is not defined" of `stomp-node.js `

I'm using node.js and use stomp-over-websocket mode. When connection closed by server side, find following exception…

/Users/foobar/node_modules/stompjs/stomp-node.js:61
      return typeof ws.onclose === "function" ? ws.onclose(error) : void 0;
                                                           ^
ReferenceError: error is not defined
    at WebSocketConnection.<anonymous> (/Users/vito/nodejs/node_modules/stompjs-http-signature/index.js:64:60)
    at WebSocketConnection.EventEmitter.emit (events.js:98:17)
    at WebSocketConnection.handleSocketClose (/Users/vito/nodejs/node_modules/stompjs-http-signature/node_modules/websocket/lib/WebSocketConnection.js:283:14)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:451:12)

Please review code at https://github.com/jmesnil/stomp-websocket/blob/v2.2.0/lib/stomp-node.js#L60-L62, a quick fix as:

connection.on('close', function() {
  return typeof ws.onclose === "function" ? ws.onclose() : void 0;
});

tks,
wenlin

Active Durable Topic Subscribers stomp.js

Hi,

we develop an application and we use web sockets. I need to put durable topics subscribers. Ths issue is that the client.connect () function of stomp.js does not allow to add the custom clientid?

Someone has a solution please?

client.send: where is the success callback?

The client.send(dst, options, body) method does not accept success callback. How can I know if the message actually sent?

I can see there is an option to provide an errorCallback to client.connect, but it won't tell me what happened exactly. For example:

client.send('someQueue', {}, 'message 1');
client.send('someQueue', {}, 'message 2');
client.send('someQueue', {}, 'message 3');

and suddneley the errorCallback fires.

How can I know if my messages were send before or after error happened? Maybe it was after message 1 and before message 2. How can I tell?

Or, the errorCallback did not fire. How long would I have to wait to make sure the messages were delivered?

No heart beat with the latest version of Code

I just got your source code downloaded. I am using Chrome browser 29.01 with Latest version of Apollo. I am getting following error message "object has no method setInterval'. I tried getting the root cause for the issue. It seems to me like stomp.js is unable to access window instance since it is using webworker. As per my understanding of Stomp it will require heart beat for keeping connection alive. Let me know if you have any solution for this.

image

Reading binary data from message body

I have an issue with reading message body which is received in binary data.
I have a valid content-length in headers but body.data is showing up empty.

{ command: 'MESSAGE',
headers:
{ timestamp: '1410215555137',
'message-id': 'ID\ccp-la-chs1-ostack2-logger1-41671-1410214441385-0\c10\c0\c0\c4',
priority: '4',
subscription: 'sub-0',
destination: '/topic/LOGGER.SYSLOG',
expires: '0',
'content-length': '8888' },
body: '',
ack: [Function],
nack: [Function] }

This looks like a bug in stompjs in reading binary data.

iOS Support

I am using ActiveMQ 5.8 and your latest library. Subscribing to topics works great in a desktop browser such as Chrome. However, in Safari for iOS such as on an iPad, it's able to connect, subscribe to topics, receive messages, but loses the connection after less than a minute. The iPad has the latest iOS version (6.1.3) and Safari is using the rfc-6455 version of websockets.

The error callback produces nothing, but in the debug output, it says "Whoops! Lost connection to ws://localhost:61614/stomp".

Unfortunately I don't have a Mac on hand at the moment, so I can't attach a cable and see the debug output from the iPad within Safari.

It produces the same problem on earlier versions of ActiveMQ too. I don't know if the issue is with your code or ActiveMQ.

Incorrect content-length with multi-byte utf-8 characters

I'm using stomp.js to send messages which contain some UTF-8 multibyte characters in their body. But the function 'Frame.prototype.toString' is only valid for single byte encoding characters ( because it use '.length' attribut ) and the header value 'content-length' becomes wrong.

ArrayBuffer is not defined in ie

solved by: change
if (evt.data instanceof ArrayBuffer) {
to
if (!(typeof(ArrayBuffer)==='undefined') &&(evt.data instanceof ArrayBuffer)) {

How can I get the last message

hi jmesnil,
I want get the last(new) message from a topic,I config the "activemq.xml" like this:

    <dispatchPolicy>  

          <strictOrderDispatchPolicy/>  
        </dispatchPolicy>  

        <subscriptionRecoveryPolicy>  

          <lastImageSubscriptionRecoveryPolicy/>  
        </subscriptionRecoveryPolicy>  
      </policyEntry>  

and set the topic like this:
destination = $("#destination").val()+'?consumer.retroactive=true';
but when I disconnect and connect again don't receive any message.
with c# can get the last message,my c# code is:
using System;
using System.Collections.Generic;
using System.Text;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace MessageSender
{
class Program
{
static void Main(string[] args)
{
try
{
//Create the Connection factory
IConnectionFactory factory = new ConnectionFactory("tcp://192.168.0.34:61616/");

            //Create the connection
            using (IConnection connection = factory.CreateConnection())
            {
                connection.ClientId = "testing listenerCCss";
                connection.Start();

                //Create the Session
                using (ISession session = connection.CreateSession())
                {
                    //Create the Consumer
                    IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("zs.www?consumer.retroactive=true"));// "testing listener", null, false);

                    consumer.Listener += new MessageListener(consumer_Listener);

                    Console.ReadLine();
                }
                connection.Stop();
                connection.Close();
            }
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    static void consumer_Listener(IMessage message)
    {
        try
        {
            ITextMessage msg = (ITextMessage)message;
            Console.WriteLine("Receive: " + msg.Text);
        }
        catch (System.Exception e)
        {
            Apache.NMS.ActiveMQ.Commands.ActiveMQBytesMessage amm = (Apache.NMS.ActiveMQ.Commands.ActiveMQBytesMessage)message;

            Console.WriteLine(amm.ToString());
        }
    }
}

}

I have no idea,may you give me a resolvent?Thanks!

Fire a callback when disconnected due to no heartbeat

I would like to see a callback fired (maybe the error callback, maybe a new one) when the connection is closed due to failed heartbeat. That would open up possibilities to attempt a reconnect, connect to a different server, or update a UI when disconnected.

Thanks for an awesome piece of code :-)
Jim

Best way to reconnect?

Hi!

I was wondering what should be the best way to reconnect after losing connection. I'm facing a case where an HTML5 app lose the connection when the mobile is going on hold.

I though calling a connect again in a connection error callback could work, but it does not. Freeze on "Opening Web Socket..."

I managed it by calling for a new connection in connection error callback. But I'm losing all my subscription so I have to store those in order to subscribe again. Not great.

I'm thinking about another thing: is heartbeat could prevent losing connection?

Does not work in SharedWorker

I'm trying to use stomp-websocket in a shared web worker, but it fails:

Uncaught ReferenceError: exports is not defined

I'm currently getting around the issue by changing the relevant code to

  if (typeof window !== "undefined" && window !== null) {
    window.Stomp = Stomp;
  } else if ( typeof self !== "undefined" && self !== null ) {
    self.Stomp = Stomp;
  } else {
    exports.Stomp = Stomp;
    Stomp.WebSocketClass = require('./test/server.mock.js').StompServerMock;
  }

I've only tested in Chromium, and I have no idea whether or not that will break Node.js... it might be better to move the self version to the end. Either way, it would probably be a good idea to make sure exports !== undefined too.

Using stomp.js over sock.js with ActiveMQ-Apollo does not seem to work

Jeff,

I am not sure where the issue may be, so, I posted on the stackoverflow.com, however, decided to also post here.

Let me know if you have seen this issue before...

http://stackoverflow.com/questions/18217327/using-stomp-js-over-sock-js-with-activemq-apollo-does-not-seem-to-work

Following the example in the stompjs document:

image

I see these two errors:

image

And the debug screen in the chat client looks like this:

image

I am serving the page from the same server on which ActiveMQ Apollo is running:

image

Just the port is different.

I am also using the latest versions of stompjs as well as sockjs clients.

Here's hoping you have some ideas...

Thanks.
-AP_

ie8 issues with Date.now()

You are using Date.now() which when run in ie8 as it is undefined. Need something like

if (!Date.now) {
Date.now = function() {
return new Date().valueOf();
}
}

Accept headers on disconnect

The disconnect method doesn't allow passing headers, just a callback, so it's impossible to pass the receipt header

loosing connection after some time

I'm using stomp-websocket connected to apache activemq websocket topic. Everything seems to work fine, I can send and receive messages, but the client keeps disconnecting with error message of:

"Whoops! Lost connection to ws://localhost:61614/ "

I can't see why this is happening and am clueless as to how to debug this.

Is there some event I could attach to a function to reconnect? Or perhaps something is not ok with heartbeat?

Missing bower.json in repo

When using the grunt-bower-install task to automatically inject Bower components into our app, we're receiving the following error:

Running "bower-install:app" (bower-install) task

stomp-websocket was not injected in your file.
Please go take a look in "public/bower_components/stomp-websocket" for the file you need, then manually include it in your file.

I believe the is due the stomp-websocket repo does not including a bower.json file with a main attribute. Here's an example - https://github.com/angular/bower-angular/blob/master/bower.json

can't create a durable topic subscribers

hi jmesnil,
I used the stomp js to create a application,it is connected successful.But I need create a durable topic subscribers,it's seems can't do this.My code is:

  var headers = {
    login: login,
    passcode: passcode,
    // additional header
    'client-id': 'my-client-id'
   };
      // the client is notified when it is connected to the server.
      //client.connect(login, passcode, function(frame) {
      client.connect(headers, function(frame) {
        client.debug("connected to Stomp");
        $('#connect').fadeOut({ duration: 'fast' });
        $('#connected').fadeIn();
        client.subscribe(destination, function(message) {
          $("#messages").append("<p>" + message.body + "</p>\n");
        });
      });
      return false;
    }); 

can you help me?
Tanks!

Overload Stomp.client to take a subprotocol

Stomp.client(url) currently does not allow specifying the subprotocol to use.

For WebSockets servers with multiple MQ protocol implementations (eg WAMP), or behind delegating private proxies (eg Varnish in front of Nginx), this is an inconvenience.

Whilst this can be done using Stomp.over(ws), it is not as convenient, and more likely for newbies to make mistakes whilst following the tutorial - especially when new browsers are in use.

Sending big message through websocket

When you send a message through Stomp Websocket using stomp.js, if you increase the size of "maxWebSocketFrameSize", to be able to send a big message without spliting, we have a "Connection Lost" if the message is bigger thank 16kb.

HTTP handshake custom headers

Hi,
I would like to send to the server custom headers as part of the HTTP handshake (CSRF header for example).
How can we do it?

Can't work with RabbitMQ 3.1.3

Hi, I'm testing stomp-websocket with RabbitMQ 3.1.3. I've already installed the Web-Stomp plugin - http://www.rabbitmq.com/web-stomp.html and got it working with via the examples provided on the RabbitMQ Web-Stomp plugin page that connects to http://127.0.0.1:15674/stomp. I'm also able to connect directly to STOMP port at 61613 using Telnet.

However, I'm not able to test it using the examples provided on https://github.com/jmesnil/stomp-websocket. I tried browsertests using the following config for url using all the ports I can find:

url : "ws://localhost:61623"
url : "ws://localhost:61623/stomp"
url : "ws://localhost:61613"
url : "ws://localhost:61613/stomp"
url : "ws://localhost:15674"
url : "ws://localhost:15674/stomp"

For all the url configured, the test fails at "9. Stomp Connection module: Connect to a valid Stomp server (1, 0, 1)"

P.S. I'm testing using a locally - not via a web server.

UTF-8 decoding is wrong

When receiving an UTF-8 string with multi-byte characters like "é" "ю" etc. it is decoded byte by byte giving the result as:

é �

Sending doesn't work at all:

SEND
destination:/topic/spr
content-length:4

ùé
<<< PONG

PING
<<< PONG
PING
<<< ERROR
message:Expected null terminator after 4 content bytes

Proposal to update the API

Jeff, thanks for the excellent library!

Regarding you comment, it would be better IMO if the API instead of this:

Stomp.WebSocketClass = SockJS;
client = Stomp.client(url);

would look like:

var ws = new WebSocket(url); // or SockJS or whatever
client = Stomp.client(ws);

This would not only remove the need to establish websocket connection within your code, but also would allow a bit more flexibility. Take a look at this blog post where I try to explain how to compose higher level abstractions out of simple websocket-like objects.

In other words: it would be cool if Stomp client could be run on the "multiplexer" objects, not only real websockets.

'headers.message' is null or not an object in IE8

I am working on a simple project with Spring Web Socket + sockjs + stompjs, and it works well in several browsers except IE8. Here are my code clips,

var socket = new SockJS("/stockticker/ws");
var stompClient = Stomp.over(socket);

// when subscribing to price topic
function renderPrice(frame) {
    ...
}

// Callback function to be called when stomp client is connected to server
var connectCallback = function() {
  stompClient.subscribe('/topic/price', renderPrice);
}; 

// Callback function to be called when stomp client could not connect to server
var errorCallback = function(error) {
  alert(error.headers.message);
};

// Connect to server via websocket
stompClient.connect("guest", "guest", connectCallback, errorCallback);

Above codes can't work in IE8, and I found some logs from IE 8 console,

LOG: Opening Web Socket...
LOG: Whoops! Lost connection to undefined
'headers.message' is null or not an object stockticker, line 54 character 7
Permission denied sockjs-0.3.4.min.js, line 27 character 1

it seems something goes wrong in sockjs firstly, and then it impact the stompjs, could you please help check this issue? Or throw me some light about how to avoid such issue in older browsers such as IE8 and IE9?

Thanks in advance.

Reconnect code

Hello Jeff,

I'm attempting to reconnect as suggested by your kind post to StackOverflow.

function stompFailureCallback (error) {
is_connected = false;
console.log('Stomp consumer: ' + error);
setTimeout(function() {stompConnect();}, 20000);
console.log('Stomp consumer: Reconnecting in 20 seconds');
}

function stompConnect() {
if (is_connected) return;
console.log('calling consumer::client.connected()');
client.connect(STOMP_LOGIN, STOMP_PASSWORD, stompSuccessCallback, stompFailureCallback);
}

I get

"Opening Web Socket..." but it never errors out, and doesn't tray to open again.

The ActiveMQ stomp server is intentionally off, so that I can test the retry.

{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }

Something is not working for the re-try...

Regardless, thank you for your nice library.

Apache/Apollo STOMP websockets authentication failure

Hi -
I'm using Apollo broker. I added a new user/password called guest/guest123 in users.properties file. I'm able to login to the broker using a PHP client (with guest/guest123). But when I use a websocket client (I used stomp-websocket/tree/master/example/chat), it gives me the an error (pl. see below for error message).

I have tried with Firefox, and Chrome. surprisingly, it works when I use admin/password. What am I doing wrong? Appreciate any help!
-PC

Opening Web Socket...
Web Socket Opened...

CONNECT
login:guest
passcode:guest123

<<< ERROR
message:Not authorized to connect to virtual host 'apollo'. Principals=[org.apache.activemq.jaas.UserPrincipal(guest), org.apache.activemq.apollo.broker.security.SourceAddressPrincipal(0:0:0:0:0:0:0:1)]

Whoops! Lost connection to ws://localhost:61623/stomp

Frame.sizeOfUTF8 different result in IE8

I followed the Using WebSocket to build an interactive web application Spring tutorial to see how WebSockets are useable in Spring.

It worked fine in current browser, but in IE8 it resulted in an error. While searching for the cause, I came across the sizeOfUTF8-method. Using the ie11 in ie8 document mode debugger I found out that the usage of String.prototype.split with an regex causes a different length in ie8 (see comparison below. Top: ie11 in ie8 document mode. Bottom: chrome).

ie11-ie8-mode
chrome

It looks like this is a known problem with older versions of ie and split: http://blog.stevenlevithan.com/archives/cross-browser-split. Using the String.prototype.split polyfill from http://blog.stevenlevithan.com/archives/cross-browser-split fixes this problem in IE8.

Could you add a note that a split polyfill is required to work in IE8 or change the sizeOfUTF8?

Cannot connect to Apollo 1.3 server: Whoops!

Connect to Apollo 1.3 server fails with the "Whoops" message. No errors in the JavaScript console and nothing in Fiddler. No errors in the Apollo log files, either. The Java client example included with Apollo works fine. Tried using stomple.js but that also fails to connect, so this may be an Apollo issue.

"heart-beat" in header arg of connect method is not being used

If a heart-beat is provided in the header argument of the 'connect' method it should be used instead of the default.

@ws.onopen = =>
@debug?('Web Socket Opened...')
headers["accept-version"] = Stomp.VERSIONS.supportedVersions()
# bug: we should only do the following assignment when headers["heart-beat"] is null
headers["heart-beat"] = [@heartbeat.outgoing, @heartbeat.incoming].join(',')
@_transmit "CONNECT", headers

add to cdnjs

Could you please add stomp.js to cdnjs so one doesnt have to manually download it to use it

rabbitmq 2.8.6 support

It would be nice to get .ez file for webstomp plugin for 2.8.6, otherwise every one has to build it from source...

now() function returns a function

Hi jsmenil,

I'm setting up the heart-beat functionality in my js app. I realized, while checking whether the "PONG" part was working as expected, that the function "now" currently implemented as :

now = function() {
  return Date.now || new Date().valueOf;
};

returns a function in case Date.now is defined in the browser. As I'm using Chrome 33.0.1750.117, the function is actually defined.
But when it is used, you expect that the function returns a number instead of being a function.
As a consequence, when the delta between now() and _this.serverActivity is set (L.189 of the stomp.js compiled file), instead of being a number, it is set to NaN. Thus, the comparison to the ttl * 2 fails, and the websocket never closes.

wild card subscriptions don't work

I'll see if I can fix this myself, but just so you know...
If I do..
client.subscribe("/topic/karlnet.>", onreceive);

Then the debug clearly shows that the messages are received, but the

var onreceive = subscriptions[frame.headers.destination];
if (onreceive) {

lines, look for an exact match, which isn't found.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.