0
votes

how to receive messages from clients to server using pubnub.

Can i subscribe to a channel and listen to it in server end(node.js)?

Need to use pubnub for following scenario:-

=> Lot of users namely, depositors and withdrawers want to send their details to "P2P" microservice via web sockets.

=> depositors and withdrawers are at client end and P2P microservice is a server end(built in node.js).

=> Now, with pubnub i'am able get this functionality such as :- server is able to publish messages to a channel and client in the browsers are able to listen to those messages through websockets.

=> But i need the opposite functionality that is , client will publish messages in a channel after subscribing to it and server(Node.js) must be able to listen to that messages.

Server.js

                const publishConfig = {
                      channel: "pubnub_onboarding_channel",
                      message: { "sender": uuid, "content": "Hello From Node.js SDK" }
                }
                pubnub.addListener({
                    message: function (message) {
                        console.log(message);
                    },
                    presence: function (presenceEvent) {
                        console.log(presenceEvent);
                    }
                });                                         // What is this listener? is it supposed to listen the messages from client? no messages are received here 

                pubnub.subscribe({
                    channel: "pubnub_onboarding_channel",
                    withPresence: true,
                });                                                                   // This function is used for subscribing to channel

                pubnub.publish(publishConfig, function (status, response) {
                    console.log(status, response);
                });                                                                   // This is to again publish to client
1
You can subscribe to a channel no matter the client "type": server, mobile, browser, IoT board, etc. But subscribing from the server side does have its challenges if you are deploying multiple server instances. There are best practices that you must follow and I would recommend contacting PubNub Support (include this SO link so we can post back here with details) to get more guidance around those best practices. But if it is single node server, it's no different than a standard client device. - Craig Conover

1 Answers

0
votes

Yes, you can certainly "publish" from the client and "subscribe" to the same channel you are publishing to from the server to enable client-to-server communication.

From the client (JavaScript) side you publish on to a channel - https://www.pubnub.com/docs/web-javascript/api-reference-publish-and-subscribe#publish

From the server (Node.js) side you subscribe to the same channel - https://www.pubnub.com/docs/nodejs-javascript/api-reference-publish-and-subscribe#subscribe