4ib3r / stompbrokerjs Goto Github PK
View Code? Open in Web Editor NEWNodeJS StompBroker
License: MIT License
NodeJS StompBroker
License: MIT License
The following code will lose the 10 characters "0123456789":
var topic ='xxx'; var data = {a:5}; stompServer.send( topic, {}, JSON.stringify({ topic, data, }) + '0123456789', );
I can't get en event to fire when a client subscribe a topic but only when on that topic a message is received. Like if on('subscribe') acts more like on ('publish'). Is there an event that fires just when a user subscribes even if no messages are sent at all ?
I also don't really get how to create a topic with the the dot notation.
for instance, I could send to topic /one/two
but not sure if I should listen to subscription to /one.two
or one.two´ or
/one/two`... could you be more explicit in the documentation or examples maybe ?
Thanks for your wonderful work.
I am using this npm package to simulate my colleage's in progress stomp broker in java. They will setup duplex heartbeat.
StompServer has mandatory argument of HttpServer. However if multiple websocket connections are needed at one http server, the websocket server needs to be setup with noServer: true
as described here:
https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server
This should be possible, so these args are passed further to ws
Server constructor:
const stompServer = new StompServer({
noServer: true
});
There is a workaround available to pass an http server which will not be used later:
const stompServer = new StompServer({
path: '/any-path',
// this is a fake server passed because stomp-broker-js does not want to pass
// { server: undefined, noServer: true } to ws library, which is supported and totally should work.
server: http.createServer()
});
Then websocket server is available anyway at stompServer.socket
, and the instruction for multiple socket connection is still able to be followed.
The node broker run in nodejs
Debugger listening on ws://127.0.0.1:9229/8e90f57c-84bd-49ce-8b41-f9e626d23132
For help, see: https://nodejs.org/en/docs/inspector
Connect id207227774120221540000
CONNECT id207227774120221540000 { client: 10000, server: 10000 } { 'accept-version': '1.0', 'heart-beat': '10000,10000' }
Server subscribe sub-1601805535061-486 /echo
topic:/echo messageType: string Bonjour { destination: '/echo',
'content-length': 7,
bytes_message: true,
subscription: 'self_15317701541' }
After the reply
I have the callstack
TypeError: Cannot read property '0' of undefined
at StompServer._checkSubMatchDest (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:495:21)
at StompServer._sendToSubscriptions (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:353:24)
at StompServer. (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:207:10)
at callNext (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:125:31)
at StompServer.onSend (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:129:14)
at StompServer. (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:389:10)
at StompServer.stompServer.subscribe (E:\nodeproject\octree\server.js:52:17)
at StompServer.emit (events.js:198:13)
at StompServer.EventEmitter.emit (domain.js:448:20)
at StompServer._sendToSubscriptions (E:\nodeproject\octree\node_modules\stomp-broker-js\stompServer.js:361:16)
When i debug i watch a wrong value in for loop of The variable i increment correctly 0 , 1 and then containt "indexOKey"
this._sendToSubscriptions = function (socket, args) {
for (var i in this.subscribes) {
var sub = this.subscribes[i];
Looks like it's called stomp-broker-js
, not stompServer
hi
stompServer.subscribe('/**', function (msg, headers) {
var topic = headers.destination
console.log(topic, '->', msg)
}, headers) <-- problem with this particular "headers"
waiting advise, thank U
In my opinion it would be great to start using GitHub releases function (powered by git tags):
https://github.com/4ib3r/StompBrokerJS/releases
Please implement sending of individual messages to stomp client.
Great thanks for your work!
Does anyone know how to use this plugin in nestjs
Server messages sent by a StompBrokerJS server don't have the destination:
header described in the STOMP protocol for server messages.
This line
Line 356 in 04ca0d3
destination:
header should be populated with the destination value instead to match the STOMP protocol.
Maybe I am mistaken?
When I use this function, I try to send a heartbeat to the client, but the following usage does not work:
const http = require('http');
const StompServer = require('stomp-broker-js');
// const node_static = require('node-static');
// const static_directory = new node_static.Server(__dirname);
const server = http.createServer((request, response) => {
console.log(request.url);
response.writeHead(200, {
'Access-Control-Allow-Origin': 'http://localhost:8080',
'Access-Control-Allow-Credentials': 'true',
// 'Content-Type': 'text/event-stream'
});
response.end('end')
// static_directory.serve(request, response);
});
const stompServer = new StompServer({
server: server,
debug: console.log,
path: '/stomp',
protocol: 'sockjs',
heartbeat: [20000, 20000]
});
console.log(' [*] Listening on 0.0.0.0:9999');
server.listen(9999, 'localhost');
stompServer.heartbeatOn(stompServer, 20000, true)
stompServer.subscribe("/subscribe", (msg, headers) => {
var topic = headers.destination;
console.log(`topic:${topic} messageType: ${typeof msg}`, msg, headers);
stompServer.send('/subscribe', headers, `Hello from server! ${msg}`);
});
Modify the source code, print the parameters of the heartbeaton function and find that it is called elsewhere,which set serverside paramter to 'false'
this.heartbeatOn = function (socket, interval, serverSide) {
var self = this;
console.log('###', socket, interval, serverSide)
if (serverSide) {
// Server takes responsibility for sending pings
// Client should close connection on timeout
socket.heartbeatClock = setInterval(function() {
if(socket.readyState === 1) {
self.conf.debug('PING');
socket.send(BYTES.LF);
}
}, interval);
} else {
// Client takes responsibility for sending pings
// Server should close connection on timeout
socket.heartbeatTime = Date.now() + interval;
socket.heartbeatClock = setInterval(function() {
var diff = Date.now() - socket.heartbeatTime;
if (diff > interval + self.conf.heartbeatErrorMargin) {
self.conf.debug('HEALTH CHECK failed! Closing', diff, interval);
socket.close();
} else {
self.conf.debug('HEALTH CHECK ok!', diff, interval);
socket.heartbeatTime -= diff;
}
}, interval);
}
};
What the console prints is
### {
on: [Function: on],
send: [Function: send],
close: [Function: close],
sessionId: 'idxx'
} 20000 false
But I found the call in other places, which is:
function FrameHandler(stompServer) {
this.CONNECT = function (socket, frame) {
// setup heart-beat feature
var rawHeartbeat = frame.headers['heart-beat'];
var clientHeartbeat = [0, 0];
if (rawHeartbeat) {
clientHeartbeat = rawHeartbeat.split(',').map(function(x) { return parseInt(x); });
}
// default server heart-beat answer
var serverHeartbeat = [0, 0];
// check preferred heart-beat direction: client → server
if (clientHeartbeat[0] > 0 && stompServer.conf.heartbeat[1] > 0) {
serverHeartbeat[1] = Math.max(clientHeartbeat[0], stompServer.conf.heartbeat[1]);
stompServer.heartbeatOn(socket, serverHeartbeat[1], true);
}
// check non-preferred heart-beat direction: server → client
else if (clientHeartbeat[1] > 0 && stompServer.conf.heartbeat[0] > 0) {
serverHeartbeat[0] = Math.max(clientHeartbeat[1], stompServer.conf.heartbeat[0]);
stompServer.heartbeatOn(socket, serverHeartbeat[0], true);
}
if (stompServer.onClientConnected(socket, {
heartbeat: clientHeartbeat,
headers: frame.headers
})) {
ServerFrame.CONNECTED(socket, serverHeartbeat.join(','), stompServer.conf.serverName);
} else {
ServerFrame.ERROR(socket, 'CONNECTION ERROR', 'CONNECTION ERROR');
}
};
Besides modifying the source code, is there any other way to send a heartbeat to the client?
Hi i am trying to validate a client using headers in the 'connected' event. Could you please let me know to avoid the connection or stop cliebt connecting if validation fails.
I am having an issue setting up a simple connection from a browser to the node example given.
Server code:
var http = require("http");
var StompServer = require('stomp-broker-js');
var server = http.createServer();
var stompServer = new StompServer({server: server});
server.listen(9999);
stompServer.on('connecting', function() {
console.log("CONNECTING")
})
stompServer.subscribe("/**", function(msg, headers) {
var topic = headers.destination;
console.log(topic, "->", msg);
});
stompServer.send('/test', {}, 'testMsg');
Browser code:
import * as Stomp from '@stomp/stompjs';
// connect to local server
const ws = new WebSocket('ws://localhost:9999');
const client = Stomp.over(ws);
client.debug = () => undefined;
client.connect(
{},
frame => {
console.log('Connected', frame);
},
(error: any) => console.log('Error', error)
);
I am just copying what is in the docs as regards the server code. I am using @stomp/stompjs client to connect.
The error I get is: WebSocket connection to 'ws://localhost:9999/' failed: Error during WebSocket handshake: Unexpected response code: 400
Currently, it contains version without SockJS adapter
I am confused about creating a server in NodeJS that can act as a broker sing STOMP protocol over WebSockets... Can this Library help me with that??
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.