Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Topic Publish Example with Hyper-Express #54

Closed
half-metal opened this issue Feb 19, 2022 Discussed in #30 · 3 comments
Closed

Topic Publish Example with Hyper-Express #54

half-metal opened this issue Feb 19, 2022 Discussed in #30 · 3 comments

Comments

@half-metal
Copy link

half-metal commented Feb 19, 2022

Hi, glad to get this working, but ran into an issue with the ws.publish, do you have an example to show a publish working as expected for this:
publish(String: topic, String|Buffer|ArrayBuffer: message, Boolean: is_binary, Boolean: compress): Publishes the specified message to the specified topic in MQTT syntax.
This is the gist of what I tried using below:

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const HyperExpress = require('hyper-express');
const Server = new HyperExpress.Server();
const Router = new HyperExpress.Router();
Server.listen(8082)
Server.ws('/', (ws) => {

    ws.id = randomUUID()
    ws.subscribe = uTopic
    connections[ws.id] = ws
    connections[ws.id].publish('locationHb', 'you are now subscribed to locationHb') // not sent to client
    ws.publish('locationHb', 'you are now subscribed to LocationHb') // not sent to client
    connections[ws.id].send('Client ID is' + ws.id) //sent to client
    console.log('Number of clients Object.keys(connections).length;', Object.keys(connections).length)
    clientCount = Object.keys(connections).length

    console.log('Client ID is:' + ws.id)
        ws.on('close', () => {
        console.log('Client ID disconnected:' + ws.id)
        delete connections[ws.id];
        })
}

This page discusses using MQTT which is good, but not seeing a clear example https://github.com/kartikk221/hyper-express/blob/master/docs/Websocket.md

I see they are subscribed, but still not receiving messages
image

Thanks

Discussed in #30

Originally posted by debshaw13 December 13, 2021
Does hyper-express have an equivalent function to broadcast (that is available in ws)? For example, using ws, the following code broadcasts data without any connections:

const wss = new WebSocket.Server({ port: 8082 });

wss.broadcast = (data) => {
  wss.clients.forEach((client) => {
    client.send(data);
  });
};

If I replace 'WebSocket' above with 'HyperExpress' (after importing 'hyper-express' of course), I see the following error:

TypeError: Cannot read property 'forEach' of undefined

Would appreciate any advice as to what I am doing wrong. Thank you for the great package, and apologies if this is a newbie question.

@half-metal
Copy link
Author

I also tried this based on what I read in the discussions
Server.publish('locationHb', 'you are now subscribed to locationHb')
But this also doesn't seem to send the message

@kartikk221
Copy link
Owner

Hi, so MQTT is essentially a URL protocol which determines how Publish/Subscribing will work between multiple parties.

The reason why your example is not working is because connections must first subscribe to a topic using the Websocket.subscribe(topic) method.

Then whenever you want to publish a message to all connections on a Server instance, you can simply do Server.publish(topic, message) to broadcast a message.

Below is a simple example of this:

const crypto = require('crypto');
const HyperExpress = require('hyper-express');
const Server = new HyperExpress.Server();

// Create an endpoint for accepting websocket connections
Server.ws('/connect', (ws) => {
    // Attach a unique identifier to each connection
    ws.id = crypto.randomUUID();
    
    // Subscribe the connection to "OUR_TOPIC_NAME"
    ws.subscribe('OUR_TOPIC_NAME');
    console.log(`Websocket Connection ${ws.id} Is Now Connected & Subscribed To OUR_TOPIC_NAME!`);
    
    // Bind any handlers here for this connection, we will bind the close handler so we can log closure
    ws.on('close', (code, message) => {
        console.log(`Websocket Connection ${ws.id} Has Disconnected!`);
    });
});

// Now you can publish a message to all connections over the "OUR_TOPIC_NAME" topic like below
Server.publish('OUR_TOPIC_NAME', 'This is a message for OUR_TOPIC_NAME subscribers!');

I'll also be adding an example for MQTT Pub/Sub in the Examples section of the documentation in the next update.

Hope this helps!

@half-metal
Copy link
Author

awesome, that works, I appreciate the example. Yes, I needed to have ws.subscribe('topic') instead of ws.subscribe = 'topic' and as you showed there Server.publish - Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants