Giter VIP home page Giter VIP logo

stompjs's Introduction

STOMP.js

Firefox, Chrome Safari, Edge NodeJS Test API docs refresh

This library provides a STOMP over WebSocket client for Web browser and node.js applications.

Please visit https://stomp-js.github.io/ for guides, FAQs and API docs.

Introduction

This library allows you to connect to a STOMP broker over WebSocket. This library supports complete STOMP specifications including all current protocol variants. Most popular messaging brokers support STOMP and STOMP over WebSockets out-of-the-box or using plugins.

Features

  • Simple API to interact with the Stomp protocol
  • Support for v1.2, v1.1 and v1.0 of the Stomp protocol
  • Support for fallback options in case of WebSocket unavailable
  • Browser and Node.js support
  • Option to use STOMP over TCP
  • Binary payload support

Usage

Browser

<!--
    JSPM Generator Import Map
    Edit URL: https://generator.jspm.io/#U2NgYGBkDM0rySzJSU1hcCguyc8t0AeTWcUO5noGega6SakliaYAYTzJAykA
  -->
<script type="importmap">
  {
    "imports": {
      "@stomp/stompjs": "https://ga.jspm.io/npm:@stomp/[email protected]/esm6/index.js"
    }
  }
</script>

<!-- ES Module Shims: Import maps polyfill for modules browsers without import maps support (all except Chrome 89+) -->
<script
  async
  src="https://ga.jspm.io/npm:[email protected]/dist/es-module-shims.js"
  crossorigin="anonymous"
></script>

<script type="module">
  import { Client } from '@stomp/stompjs';

  const client = new Client({
    brokerURL: 'ws://localhost:15674/ws',
    onConnect: () => {
      client.subscribe('/topic/test01', message =>
        console.log(`Received: ${message.body}`)
      );
      client.publish({ destination: '/topic/test01', body: 'First Message' });
    },
  });

  client.activate();
</script>

NodeJS

$ npm install @stomp/stompjs ws
import { Client } from '@stomp/stompjs';

import { WebSocket } from 'ws';
Object.assign(global, { WebSocket });

const client = new Client({
  brokerURL: 'ws://localhost:15674/ws',
  onConnect: () => {
    client.subscribe('/topic/test01', message =>
      console.log(`Received: ${message.body}`)
    );
    client.publish({ destination: '/topic/test01', body: 'First Message' });
  },
});

client.activate();

Further information

The API documentation is hosted as GitHub pages for the StompJS family of libraries. You may head straight to the https://stomp-js.github.io/api-docs/latest/

This library comes with detailed usage instructions. Please find it at Usage instructions. Check out other guides at https://stomp-js.github.io/.

There is quite detailed API documentation, you should start at https://stomp-js.github.io/api-docs/latest/classes/Client.html.

Upgrading

if you were using an older version of this library, you would need to make changes to your code. Head to Upgrading.

Usage with RxJS

https://github.com/stomp-js/rx-stomp is based on this library and exposes the entire functionality offered by this library as RxJS Observables.

TypeScript definitions

The npm package includes TypeScript definitions, so there is no need to install it separately.

Change-log

Please visit Change Log.

Contributing

If you want to understand the code, develop, or contribute. Please visit How to contribute.

Authors

License

License - Apache-2.0

stompjs's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dlangerenken avatar genadis avatar greenkeeper[bot] avatar imitaka avatar kum-deepak avatar lovemewithoutall avatar sailai 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

stompjs's Issues

TypeError: this.configure is not a function when calling the Client constructor

Hi, I'm trying to implement StompJs in my React App, but when I call the constructor it gives me this TypeError:

TypeError: this.configure is not a function
node_modules/@stomp/stompjs/bundles/stomp.umd.js:562

My implementation looks something like this:
import * as StompJS from '@stomp/stompjs'
const ws = StompJS.Client({
brokerUrl: 'ws://...'
});

The weird thing is if I use the deprecated format it does run and connects to my websocket API.

This implementation works:

import * as StompJS from '@stomp/stompjs'
const ws = StompJS.Stomp.client(ws://...);

I'm using v5.3.0-beta1 of StompJs

Is there something I'm missing here?

Browser: Provide a way to use stompjs from TypeScript without modules

See: #24 (comment) for a workaround

My situation is this: I want to avoid stuff like webpack and so on, instead, I have this in my <head>:

<script type="text/javascript" src="js/jquery.js"></script>                                                                                                                                                              
<script type="text/javascript" src="js/stomp.umd.min.js"></script>                                                                                                                                                       
<script type="text/javascript" src="js/common.js"></script>                                                                                                                                                              
<script type="text/javascript" src="js/chat.js"></script>

And module is set to none in my tsconfig.json.

In this specific case, my TypeScript project resides in a completely different folder and has that "js/" directory as the outDir.

For jQuery, this:

npm i --save-dev @types/jquery

is enough to get jQuery type checking, autocompletion etc. in my .ts files, thanks to this declaration:

declare const jQuery: JQueryStatic;
declare const $: JQueryStatic;

Now when I add stompjs to the TS project:

npm i --save-dev @stomp/stompjs

Nothing of sort becomes available; it looks like StompJs 100% hard depends on module loading when it comes to TypeScript.

According to the docs, including stomp.umd.min.js does give you a globally accessible StompJs object, but it does not look like there's a way to use it with type checking from TypeScript.

IE11: Websocket never opens

When using [email protected] the client never manages to connect to the server.
Debug logs (with debug: true) tell me "Opening Web Socket..." and then nothing ever happens. No error, no message or anything like that.
On Chrome everything works fine.

Few APIs alter the headers argument

The code should create a copy before updating arguments. Callers would typically expect an argument to not get updated as a side effect.

Test cases will need to be added and code reviewed to cover all such cacses.

connectHeader is not passed to Spring server

Hello!

I have the following code, using the stomp js client:

this.client = new Client();
this.client.configure({
  brokerURL: 'ws://localhost:8443/api/wsocket',
  connectHeaders: {
    login: "user",
    passcode: "password"
  },
  onConnect: () => {
    console.log('onConnect');

    this.client.subscribe('/ws/quote', message => {
      console.log(message);
      debugger;
    });
  },
  // Helps during debugging, remove in production
  debug: (str) => {
    console.log(new Date(), str);
  }
});
this.client.activate();

I was following your stomp-spring-react project on github. The problem is that I don't receive the header on the server side. I have a JWT Authentication Filter, that gets hit, but I don't get the header payload when I want to access it via: request.getHeader. I checked all the header names using request.getHeaderNames but I don't see it there either. Is this a bug or am I missing something here?

Basic Authentication

i am creating a simple chat application and the chat-api is using websocket to connect and stomp protocol.

but in my case the authentication is using "Basic Authentication".
do you have an idea on how to do it?

thanks,

Setting new connection params before re-connect

Hello all,

We're currently sending a JWT as part of our connection string (we could use a header instead). This works as expected both in the client and in the server (authenticating the token).

Anyway, since those JWTs expire, we'd like a mechanism to update our connection string (or header) whenever the Client is in the re-connection phase. Right now, the reconnection is performed using the same (probably expired) token used at the very first connection attempt.

Is there any official approach to achieve that?

Could we use the "beforeConnect" hook to do that?

Thanks in advance.

How to subscribe to temporary queue

How the stomp documentation in rabbitMQ says, it's possible to send a message and specify a temporary queue valid per session. https://www.rabbitmq.com/stomp.html#d.tqd

The documentation also says that stomp automatically subscribes to that queue. How is possible to receive messages from that queue using this client? Where can be defined the callback for messages sent to that queue which should be subscribed?

Due date for 5.0.0 or RC?

Hello,

We're eager on adding this library into our production build but we don't want to add it while tagged as "beta".

The current milestone has no due date set so the question is: is there an estimate on when RC o final will be available?

Thanks in advance.

impossible to use in the project

The string in instruction var Stomp = require('@stomp/stompjs'); doesn't work. It tries to include index.d.ts file and there is no export variable Stomp. So Stomp is undefined

TextEncoding polyfill in browser

Using v5.3.0 of this client in a typescript project that's ultimately compiled and then served by a nginx server raises an issue with the TextEncoding\TextDecoding polyfill as they do not work/are not present in the browser.
This issue is present in both IE11 and MS Edge.

I am not actually a FE dev but I suspect the fix is making use of the ployfill in spec/config/browser-config.js as it is done with node-config.js.

if (typeof TextEncoder !== 'function') {
  const TextEncodingPolyfill = require('text-encoding');
  TextEncoder = TextEncodingPolyfill.TextEncoder;
  TextDecoder = TextEncodingPolyfill.TextDecoder;
}

Looking closer, it seems spec is just for tests and not actual runtime.

Node Version

I've forked this repo and can't get an initial build.

node_modules/@types/node/index.d.ts:6539:15 - error TS2720: Class 'Duplex' incorrectly implements class 'Writable'. Did you mean to extend 'Writable' and inherit its members as a subclass?
  Property 'pipe' is missing in type 'Duplex'.

6539         class Duplex extends Readable implements Writable {

Based upon this I assume there's a node version mismatch. What version of node has been targeted for this project? I've tried v8.12.0 (LTS) and v10.11.0 (current).

Am i overlooking something simple?

Can't update client config after activate

Reproducing test:

describe("Client config", function () {
 let client;

 beforeEach(function () {
   client = new StompJs.Client({
     brokerURL: TEST.url,
     debug: console.log
   });
 });

 afterEach(function () {
   disconnectStomp(client);
 });

 it("Update client headers", function (done) {
   // working
   client.connectHeaders = {
     login: TEST.login,
     passcode: TEST.password,
     testHeader: 'testHeader_BEFORE_activate'
   };
   client.disconnectHeaders = {
     testHeader: 'testHeader_BEFORE_activate'
   };
   client.activate();

   // not working
   client.connectHeaders = {
     login: TEST.login,
     passcode: TEST.password,
     testHeader: 'testHeader_AFTER_activate'
   };
   client.disconnectHeaders = {
     testHeader: 'testHeader_AFTER_activate'
   };

   done();
 });

 it("Configure client", function (done) {
   // working
   client.connectHeaders = {
     login: TEST.login,
     passcode: TEST.password,
     testHeader: 'testHeader_BEFORE_activate'
   };
   client.disconnectHeaders = {
     testHeader: 'testHeader_BEFORE_activate'
   };
   client.activate();

   // not working
   client.configure({
     brokerURL: TEST.url,
     debug: console.log,
     connectHeaders: {
       login: TEST.login,
       passcode: TEST.password,
       testHeader: 'testHeader_AFTER_activate_configure'
     },
     disconnectHeaders: {
       testHeader: 'testHeader_AFTER_activate_configure'
     }
   });

   done();
 });

});

window is not defined

After doing all the necessary steps in the usage instructions section, only requiring stompJs leads to an error:
abc.js:
const WebSocket = require('websocket').w3cwebsocket;
const StompJs = require('@stomp/stompjs');

$ node abc.js
c:\Users....\Desktop\node_test\node_modules@stomp\stompjs\bundles\stomp.umd.js:10
})(window, function() {
^
ReferenceError: window is not defined
at Object. (c:\Users....\Desktop\node_test\node_modules@stomp\stompjs\bundles\stomp.umd.js:10:4)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object. (c:\Users....\Desktop\node_test\abc.js:2:17)
at Module._compile (module.js:652:30)

ref: https://stomp-js.github.io/guide/stompjs/2018/06/28/using-stompjs-v5.html

Error while sending heartbeat

An error in sending heartbeat breaks the whole process. It would be great if this could be handled. It happens then server drop session and client try to send heartbeat to server. In my case I want possibility to schedule a reconnect when this happens or this can be done by default.

...\node_modules\websocket\lib\W3CWebSocket.js:113
        throw new Error('cannot call send() while not connected');
        ^

Error: cannot call send() while not connected
    at W3CWebSocket.send (...\node_modules\websocket\lib\W3CWebSocket.js:113:15)
    at Timeout._onTimeout (...\node_modules\@stomp\stompjs\esm5\stomp-handler.js:162:34)
    at ontimeout (timers.js:386:11)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5)

Redesigning next generation stompjs

As the history goes, the original JavaScript implementation of the STOMP protocol was maintained by Jeff Mesnil at https://github.com/jmesnil/stomp-websocket. He retired from the project few years back. The original code got forked by many as this library was used quite heavily.

A fork is getting maintained at https://github.com/stomp-js/stomp-websocket. Major work carried out:

  • Auto reconnect
  • Documentation revamp
  • NodeJS support aligned to browser version (no hacks required)
  • Minor upgrades to build and test infrastructure

In addition, a version specialized for Angular 2+ is getting maintained at https://github.com/stomp-js/ng2-stompjs which exposes nearly all STOMP features in RxJS/Angular way.

At this stage a rework in the original library is getting planned. Following is the current outline:

Please add yourself or anyone else who would like to be part of this activity. ๐Ÿ˜ƒ

undefined when importing

In version 5, in a frontend project compiled with babel/webpack

import StompJs from '@stomp/stompjs/esm5';

results in undefined. The same with esm6

React Native - warn message sends Can't find variable: TextEncoder

I am using Stompjs to connect with Apache ActiveMQ and Spring Server but when I run application I receive a console warning message and after I navigate to another Screen with lots of data I receive this error non-stop as if it went to a loop.

Error:

 [Unhandled promise rejection: ReferenceError: Can't find variable: TextEncoder]
- node_modules/@stomp/stompjs/bundles/stomp.umd.js:1538:30 in Parser
- node_modules/@stomp/stompjs/bundles/stomp.umd.js:1832:16 in start
- ... 13 more stack frames from framework internals

I believe this has to do with the package rather than my code

const stompConfig = {
    reconnectDelay: 100,
    heartbeatIncoming: 0,
    heartbeatOutgoing: 0,
    debug: function(str) {
      console.log(str);
    }
  }

  stompConfig.webSocketFactory = () => {
    return new SockJS(
        "http://192.168.1.2:8080/"
    );
  };
  client = new Client(stompConfig);

  client.onConnect = function(frame) {
    console.log('frame', frame.body);
  };

  client.onStompError = function(frame) {
    console.log('Broker reported error: ', frame.headers['message']);
    console.log('Additional details: ', frame.body);
  };

  client.activate();

"Cannot read property 'over' of undefined"

hey ,
im getting an exception Cannot read property 'over' of undefined once i tryi to connect to the socket ,
in the older version it was working

this.socket = new WebSocket(this.url);
this.stompClient = new Stomp.over(this.socket);

Connected to server undefined - misleading

const client = Stomp.over(() => new WebSocket('wss://some-url'));

client.heartbeat.outgoing = 20000;
client.heartbeat.incoming = 0;
client.reconnect_delay = 3000;
client.connect();

image

Consider IFrame, IMessage, ITransaction interfaces

Sometimes we can get tricky errors because of private members not matching. Suggested way to avoid is to create Interfaces corresponding to those classes.

In particular Message and Transactions are not created by calling constructors. Objects are created first and claimed to be a Message/Transaction.

DOMException: Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. 'http' is not allowed.

DOMException: Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. 'http' is not allowed.
There's a kind of websocket has http: schema.
In old stomp

 var host = "http://192.168.0.1/bullet";
 var socket = new SockJS(host + '/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log('Connected:' + frame);
            stompClient.subscribe('/toAll/bulletScreen', function (response) {
                showResponse(response.body);
            });
        });

Which Spring cloud gateway can proxy.
Please add to the url check.

BinaryBody & ActiveMq

Hi, first of all great work on the library.

I am having trouble with using the library with ActiveMQ for Binary Bodies

if (data) {
	binaryData = new TextEncoder().encode(JSON.stringify(data))
}

client.publish({
	destination: '/topic/' + topic,
	binaryBody: binaryData,
	headers: {
		'content-type': 'application/octet-stream'
	}
})

I see in Chrome dev tools as the binary frame being sent however nothing is received on activeMQ. I am suspecting that it is activeMQ configuration however all I can find is this:

Stomp is a very simple protocol - that's part of the beauty of it! As such, it does not have knowledge of JMS messages such as TextMessage's or BytesMessage's. The protocol does however support a content-length header. To provide more robust interaction between STOMP and JMS clients, ActiveMQ keys off of the inclusion of this header to determine what message type to create when sending from Stomp to JMS. 

I tried adding explicitly the content-length but still to no avail. Is there something which I'm missing out?

Error retrieving message content in large messages

Hello,

I'm experiencing an issue when retrieving "large" messages using the latest 5.0.0-b4 version of the library.

The error is:

core.js:1673 ERROR SyntaxError: Unexpected end of JSON input
   at JSON.parse (<anonymous>)
   at MESSAGE (stomp-handler.js:54)
   at Parser.onFrame (stomp-handler.js:110)
   at Parser.push../node_modules/@stomp/stompjs/esm6/parser.js.Parser._retrievedBody (parser.js:171)
   at Parser.push../node_modules/@stomp/stompjs/esm6/parser.js.Parser._collectBodyFixedSize (parser.js:164)
   at Parser.push../node_modules/@stomp/stompjs/esm6/parser.js.Parser.parseChunk (parser.js:76)
   at WebSocket._webSocket.onmessage [as __zone_symbol__ON_PROPERTYmessage] (stomp-handler.js:119)
   at WebSocket.wrapFn (zone.js:1188)
   at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421) 

I'm receiving a frame (like the one attached to this issue) that is bigger than 5Kb. The collectBodyFixedSize function is trying to collect the body but it's not succeding at all.

Running a JSON.parse(message.body) is failing and I can see that this function is not retrieving the whole set of bytes of the body: it's collecting all but the 2 latest characters ("[}") of the body, making the JSON.parse fail.

I can't not reproduce this bug in smaller messages (50, 100... bytes or so) and this bug is not present in older versions (4.0.8).

Is this a real bug? Am I doing something wrong? Is this an error related to this beta version?

Thanks in advance.

message.txt

TypeError: Cannot read property 'publish' of undefined

while running my producer.js I get the following error ->
command : node stomjs/producer.js
response:
/home/dibyajyoti/Desktop/Feed/node_modules/@stomp/stompjs/bundles/stomp.umd.js:506
this._stompHandler.publish(params);
^

TypeError: Cannot read property 'publish' of #undefined
at Client../src/client.ts.Client.publish (/home/dibyajyoti/Desktop/Feed/node_modules/@stomp/stompjs/bundles/stomp.umd.js:506:28)
at Object. (/home/dibyajyoti/Desktop/Feed/stomjs/producer.js:43:8)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad #(internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

I'm using it with activemq, it's getting connected but throwing error while sending a message!
my stomp configuration is:

`global.WebSocket = require("ws");

const Stomp = require("@stomp/stompjs");

if (typeof TextEncoder !== "function") {
const TextEncodingPolyfill = require("util");
TextEncoder = TextEncodingPolyfill.TextEncoder;
TextDecoder = TextEncodingPolyfill.TextDecoder;
}

const stompConfig = {
brokerURL: "ws://localhost:61614/ws",
connectHeaders: {
login: "username",
passcode: "password"
},
debug: function(message) {
console.log(message);
},
onWebSocketClose: function(message) {
console.log("Reason: ", message.reason);
},
onWebSocketError: function() {
console.log("Web socket error");
},
onConnect: function(frame) {
console.log("Client connected to", frame.headers.server);
},
onDisconnect: function() {
console.log("Client disconnected");
},
onStompError: function(frame) {
console.log("Broker reported error: " + frame.headers["message"]);
console.log("Additional details: " + frame.body);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000
};

const client = new Stomp.Client(stompConfig);
client.activate();
client.publish({ destination: "/queue/test", headers: { priority: 9 }, body: "Hello, STOMP" });`

WebSocket is not defined (Node + Webpack)

Hello,

I am getting the following error in a Node application:

STOMP: connected to server ...
STOMP: send PING every 10000ms
STOMP: check PONG every 10000ms
STOMP: Received data
STOMP: <<< PONG
STOMP: Received data
STOMP: <<< PONG

/myproject/node_modules/@stomp/stompjs/bundles/webpack:/StompJs/src/stomp-handler.ts:251
        if (this._webSocket.readyState === WebSocket.OPEN) {
                                           ^
ReferenceError: WebSocket is not defined
    at Timeout._onTimeout (/myproject/node_modules/@stomp/stompjs/bundles/webpack:/StompJs/src/stomp-handler.ts:251:44)
    at listOnTimeout (internal/timers.js:535:17)
    at processTimers (internal/timers.js:479:7)

As you can see, the WebSocket is opening just fine, and pings are coming in normally. The error is thrown after a couple of pings have arrived, I'd say 10 seconds after the socket has opened.

WebSocket should be defined as I have the following safeguards:

  1. At the beginning of the app:
import * as WebSocket from 'ws';
  1. In my Webpack configuration file:
  plugins: [
    new webpack.ProvidePlugin({
      WebSocket: 'ws'
    }),
  ],

I currently resolve this by following the workaround mentioned in a (most likely) related issue:

Object.assign(global, { WebSocket: require('ws') });

All the best, and keep up the great work !

Issues instantiating client using v5.0.0.

I was working with the version 5.0.0.-beta.4 under an angular project, and my code works successfully.

The same code is crashing since I have updated my package.json in order to use the latest released version 5.0.0.)

this is the error I get:

core.js:1673 ERROR TypeError: Cannot set property 'binaryType' of null
    at Client.push../node_modules/@stomp/stompjs/esm5/client.js.Client._createWebSocket (client.js:175)
    at Client.push../node_modules/@stomp/stompjs/esm5/client.js.Client._connect (client.js:125)
    at Client.push../node_modules/@stomp/stompjs/esm5/client.js.Client.activate (client.js:110)

can anybody help me?

Polyfills for node.js + TS + webpack project

Hi, I found some issues when using this lib in my TS project.

  • pre installed 'websocket' lib needs .node c++ compiled module, it's not compatible in webpack, I tried 'ws' instead of 'websocket', and it seems work.
  • another dependency in node env is 'text-encoding', it's too large, I want compiled .js to be smaller. thus, is there an alternative to 'text-encoding' ?

Here is my workaround in TS to avoid errors from compiler

  Object.assign(global, { WebSocket: require('ws') });

  if (typeof TextEncoder !== 'function') {
    const TextEncodingPolyfill = require('text-encoding');
    Object.assign(global, { TextEncoder: TextEncodingPolyfill.TextEncoder});
    Object.assign(global, { TextDecoder: TextEncodingPolyfill.TextDecoder});
  }

Workaround - React Native STOMP issue because NULL chopping

I was facing an issue where the stomp client doesn't get connected to server because of the null terminator and the connect message wasn't parsed at server side correctly because it was sent as string instead of binary array.

I did lots of debugging on it and the solution was to make isBinaryBody always true
like so

FrameImpl.prototype.serialize = function () {
       var cmdAndHeaders = this.serializeCmdAndHeaders();
       if (this.isBinaryBody || true) { // to always return as binary array
           return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer;
       }
       else {
           return cmdAndHeaders + this._body + byte_1.BYTE.NULL;
       }
   };

Progress and plan

The following is a tentative list of plan:

Infrastructure:

  • Documentation - consider http://typedoc.org/ and https://compodoc.app/. ng2-stompjs uses compodoc, so would be preferable.
  • Test infra - currently it uses QUnit, consider moving to Jasmine/Karma, will get aligned to ng2-stompjs.
  • Travis CI - configure to test on Node, Firefox, Chrome. Consider using Saucelabs for IE/Edge/Safari.

Improvements:

  • Binary payload support
  • Remove Stomp class (Client should be usable directly)
  • The connect and disconnect calls should not take any parameters. All parameters should be settable at the time of construction of Client or individually settable/getable.
  • Refactor callbacks, include error/before connect/before reconnect/before disconnect/ etc.
  • Test case for large STOMP Frame

Feel free to suggest more.

@JimiC @fpozzobon @jmls

one by one processing

When I work with queues, my subscriber receives records one by one, but the next element comes to me without waiting for the operation to complete with the previous one. I tried to add the ack in the expectation that the processing will become consistent, but this did not happen. in my code, everything is built on async/await, so I have to somehow configure the framework. what am I doing wrong?

subscribe Command, i cann't get the callback

subscribe Command, i cann't get the callback
for example:
var topic="12345" stompClient.subscribe(topic, function (message) { if (message.body) { console.log('stompClient.connected subscribe...'); console.log("got message with body " + message.body) } else { console.log('stompClient.connected subscribe ot empty message...'); showGreeting("subscribe", topic, ""); } }, {id: window.uuid, destination: topic});

stomp DISCONNECT frame and websocket DISCONNECT cause error on spring boot backend

I am using

    "@stomp/stompjs": "5.2.0",
    "text-encoding": "0.7.0",
    "websocket": "1.0.28"

with react-native, a spring boot backend and activemq as the broker. It is working fine so far. But when the connection is closed through "Client.deactivate()" Spring almost always tells me, that the CloseStatus is PROTOCOL_ERROR

I tried to narrow it down, and found this answer:
https://stackoverflow.com/a/35759769/7775707

I am affected by this. When I save the socket in the factory and close it manually I don't get the exception on the backend (and I also don't get the onStompError callback). But of course that leaves the Client in a pretty ugly state where I run into uncatchable websocket errors.

Would it be possible to extend the config to not send the DISCONNECT frame, but do a hard websocket disconnect?

Or maybe you have another solution for my problem.

If necessary I could try to create a simplified test setup to demonstrate the problem. I guess this would be possible without react-native.

Client.debug message does not contain body

When writing the debug message to console - the content-length is written two times rather than the body of a message.

using

client.debug = (msg) => {
  console.log(msg);
};

the msg string - does not have the body to be written to console.

Node.js, activemq, binary body

Reported by @parmy, extracted from #22

Hi

Thanks for providing a great library, even though I haven't quite got it to work yet.

I'm hoping to connect to a ActiveMQ server, which will send GZIP messages.

I tried:

https://github.com/easternbloc/node-stomp-client
Following an article I read here:
https://medium.com/@mackplevine/using-activemq-with-node-js-stomp-and-http-b251ce8d995

I manage to connect to the client using the package, with the following:


	var options = {
		address: 	        'some url',
		port: 		'61613',
		user: 		'username',
		pass: 		'password',
		protocolVersion: '1.0' <-- could also be '1.1'
	}

var stompClient = new require('stomp-client')(options);

stompClient.connect(function(sessionId) {
    	stompClient.subscribe('/topic/...', function(body, headers) {
        }
})

I manage to make a connection and it's stable. However, without a major overhaul the stomp-client project cannot process message bodies which are sent compressed (gzip).

I came across your library, which appears to handle binary messages. However, I'm unable to connect to the ActiveMQ server.

Here's my attempt:

	var client = StompJs.Stomp.over(options["address"] + ":" + options["port"]);

	client.connect(options["user"], options["pass"], 
		function(e) {
			//connect
			console.log(e);
		}, function(err) {
			//error
			console.log(err);
		}, function(e) {
			//close
			console.log(e);
		}
	);

I've tried various things options with address, prefixing it with "ws://" and without. stomp-client didn't require "ws://".

I'm running this in a node client and I get the following error message:

Opening Web Socket...
(node:3858) UnhandledPromiseRejectionWarning: TypeError: Cannot create property 'binaryType' on string 'darwin-dist-44ae45.nationalrail.co.uk:61613'
    at CompatClient../src/client.ts.Client._createWebSocket (...app/index/node_modules/@stomp/stompjs/bundles/stomp.umd.js:422:30)
    at CompatClient.<anonymous> (...app/index/node_modules/@stomp/stompjs/bundles/stomp.umd.js:361:48)
    at step (...app/index/node_modules/@stomp/stompjs/bundles/stomp.umd.js:165:23)
    at Object.next (...app/index/node_modules/@stomp/stompjs/bundles/stomp.umd.js:146:53)
    at fulfilled (...app/index/node_modules/@stomp/stompjs/bundles/stomp.umd.js:137:58)
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:3858) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3858) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

When I try

var client = StompJs.Stomp.client(options["address"] + ":" + options["port"]);

I get the following error:

"(node:4111) UnhandledPromiseRejectionWarning: ReferenceError: WebSocket is not defined"

I can confirm I've installed websocket using npm.

Any suggestions please?

Thank you.

Issue in Using with ReactNative, NULL chopping

I am trying to integrate STOMP on my reactNative Project...
When I open my debug mode everything works fine but when i close my debug mode and run it normally it is not able to fetch data//

alert('Component did mount');
client.configure({
brokerURL: 'ws://x.x.x.x:xxxx/stomp',
onConnect: () => {
alert('onConnect');

    client.subscribe('topic', message => {
      console.log('show msg...',message);
      console.lo('show msg body...',message.body);

    });

    client.subscribe('topic', message => {
      console.log(message);
    
    });

    
  },
  
});

client.activate();

How to install via NPM (TypeScript Node.js Project)

Hello,

thanks for creating this library! I'm very happy about the transition to TypeScript, btw.

Maybe I've overlooked something grand, but I didn't found the version 5 of stompjs on NPM. How would you install and use this with a TypeScript Node.js project?

Best,
Simon

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.