jmesnil / stomp-websocket Goto Github PK
View Code? Open in Web Editor NEWStomp client for Web browsers and node.js apps
Home Page: http://jmesnil.net/stomp-websocket/doc/
License: Apache License 2.0
Stomp client for Web browsers and node.js apps
Home Page: http://jmesnil.net/stomp-websocket/doc/
License: Apache License 2.0
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)
Since Stomp.js supports sending fragmented STOMP frames (#36), it should support receiving fragmented STOMP frames as well.
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.
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.
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.
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.
Is there any way I can access the entire message body when it is split into multiple continuation frames?
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!
To use SockJS (see http://www.rabbitmq.com/blog/2012/05/14/introducing-rabbitmq-web-stomp/ ), this used to just work :
WebSocketStompMock = SockJS;
However, recent stomp.js
is not working with this. (as of commit d1f600611e
)
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.
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
According to https://activemq.apache.org/stomp.html header line "content-length" determs which message type JMS client will be accepted.
https://github.com/jmesnil/stomp-websocket/blob/master/lib/stomp.js#L39 has hard code for it. So can it be configurable?
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.
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.
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?
Sub-task of #9.
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.
Could you please add stomp.js to cdnjs so one doesnt have to manually download it to use it
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?
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
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();
}
}
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
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?
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
https://www.npmjs.org/package/stomp
seems to be outdated, would it be possible to update it?
thanks!
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.
The below code state is stopping the UI from loading in IE 9 and FF 30 as there is no condition whether the console is open or not. However, works in Chrome and FF 29
this.debug("Opening Web Socket...");
Any workaround as this might be a common issue.
Is there any failover configuration support in StompJS. We are trying to connect to ActiveMQ cluster and as per http://activemq.apache.org/failover-transport-reference.html the client should use failover tranport url of the format
failover:(ws://primary:61616,ws://secondary:61616)?randomize=false
I encountered this error when trying to run the webworker example against RabbitMQ SockJS. I'm using the latest Chrome Version 33.0.1750.154.
The disconnect method doesn't allow passing headers, just a callback, so it's impossible to pass the receipt header
if you could contribute a typescript definition file to the definitely typed repo it would be very helpful.
https://github.com/borisyankov/DefinitelyTyped
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.
add support for Stomp 1.1
solved by: change
if (evt.data instanceof ArrayBuffer) {
to
if (!(typeof(ArrayBuffer)==='undefined') &&(evt.data instanceof ArrayBuffer)) {
@maxWebSocketFrameSize variable name could be confusing since it is more about Websocket message size. I propose to rename @maxWebSocketFrameSize to @maxWebSocketMessageSize and update related comments.
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
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.
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?
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!
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
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?
It would be nice to get .ez file for webstomp plugin for 2.8.6, otherwise every one has to build it from source...
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.
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.
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.
This is quite simple to do but unfortunately only you really should do it!
Happy to help if it helps.
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...
Following the example in the stompjs document:
I see these two errors:
And the debug screen in the chat client looks like this:
I am serving the page from the same server on which ActiveMQ Apollo is running:
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_
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
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).
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
?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.