Issue setting up Pubnub Nodejs server - node.js

Following the example from:
https://www.npmjs.org/package/pubnub
I am trying to set up a connection from my nodejs server to pubnub via:
var pubnub = require("pubnub").init({
publish_key: "pub key here",
subscribe_key: "sub key here",
channel: 'my_channel',
user: 'Server'
});
pubnub.subscribe({
channel: 'my_channel',
callback: function(message) {
console.log("Message received: ", message);
}
});
pubnub.publish({
channel : 'my_channel',
callback : function(e) { console.log( "SUCCESS!", e ); },
error : function(e) { console.log( "FAILED! RETRY PUBLISH!", e ); }
});
// test msg to see if server connect to pubnub channel
function publish() {
pubnub.publish({
channel : 'my_channel',
message : 'Server subscribed'
});
}
I thought this followed the example provided but my server will not show up in the pubnub log nor receive any SocketIO events from the 2 peers trying to connect to each other. I am trying to use pubnub with SocketIO to send over ice candidates to establish p2p video via WebRTC
For peers that are trying to connect that are actually do have a pubnub connection working, the set up is as follows:
(function() {
var pubnub_setup = {
channel: "my_channel",
publish_key: "pub key",
subscribe_key: "sub key",
user: user
};
var socket = io.connect( 'http://pubsub.pubnub.com', pubnub_setup);
// various socket.on( ... )
})();

#jerryfox, there is a connection callback on subscribe called "connect". You should only issue your test publish on this "connect" callback... otherwise, you can publish before you've actually connected, and you'll never see the message. Try this:
pubnub.subscribe({
channel: 'my_channel',
callback: function(message) {
console.log("Message received: ", message);
},
connect: publish
});
If you are still having issues, contact us at support#pubnub.com, and we'll help resolve the issue for you.

Related

mqtt client disconnected when subscribe with thingsboard topic

I am trying to make a connection with thingsboard by subscribing to a topic so that I can receive an updated state changes. But after subscription the client seems to be disconnected. Below is my code
const mqttEndpoint = 'MyLocalIpAddress:1883'
const MQTT_TOPIC = 'v1/devices/me/attributes'
const mqttClient = mqtt.connect(`mqtt://${mqttEndpoint}`, {
username: '123456789asdf',
rejectUnauthorized: false,
})
mqttClient.on('connect', function () {
mqttClient.subscribe(MQTT_TOPIC, function (err) {
if (!err) {
console.log('subscribed')
}
})
})
mqttClient.on('message', (topic, message) => {
// message is Buffer
console.log('topic', topic);
console.log('message', message.toString());
//this.server.emit('msgToClient', message.toString());
mqttClient.end()
})
mqttClient.on('close', () => {
console.log('mqtt: connection closed');
})
I think the javascript mqtt code seems to be ok. But I am not figuring it out how can receive an update state from the thingsboard via mqtt.
The events in the console while running the above code:
Processing connect msg for client: mqttjs_f7181153!
Processing connect msg for client with user name: 123456789asdf!
Client connected!
subscribed
Client disconnected!
Also I had tried it with mosquitto but seems to be the connection is successful but not receiving anything if there is an update in state
mosquitto_sub -d -h "localhost" -t "v1/devices/me/attributes" -u "123456789asdf"

Send notification to disconnected user using socket io

I am new in socket development. I am creating chat using socket io, frontend is ios and backend is node js. I want to send message notification for disconnected users. Like we get notification if whatsapp is not opened. How can I do that ?
You can catch the person's exit with Socket.io and send a notification with push.js
socket.on('disconnect', function () {
console.log('user disconnected');
Push.create(data.user_name + " | Chat", {
body: data.desc,
icon: "https://pushjs.org/images/icon.png",
tag: "chat",
link: "http://localhost:8080/chat",
timeout: 5000,
onClick: function () {
window.focus();
this.close();
}
});
});

Is there any way to receive event when new client connect and disconnect?

We are using node as a server and mqtt as a library.
we installed mosquitto as a brocker for web socket.
Now we have to track record when new client connect and disconnect but problem is that we unable to get any event.
so Is there any way to achieve this ?
const mqttServer = require('mqtt');
const clientId = appName + "_" + moment().valueOf();
const conOptions = {
clientId,
username: mqtt.user,
password: mqtt.pass,
keepalive: 10,
clean: false,
rejectUnauthorized: false
};
const conUrl = mqtt.uri;
const mqttClient = mqttServer.connect(conUrl, conOptions);
mqttClient.on("error", (err) => {
logger.error(`${chalk.red('✗')} MQTT Error : `, err);
});
mqttClient.on('offline', () => {
logger.error(`${chalk.red('✗')} MQTT Offline`);
});
mqttClient.on('reconnect', () => {
logger.error(`${chalk.red('✗')} MQTT Reconnect`);
});
mqttClient.on('connect', () => {
logger.info(`${chalk.green('✓')} MQTT Connected with ClientID ${chalk.yellow(clientId)}`);
});
mqttClient.on('message', (topic, message) => {
logger.error(`New message in MQTT : ${message.toString()} on ${topic}`);
});
Why not just have each client publish their own message when they connect/disconnect.
This allows you to control exactly what is in the message.
You can send the disconnect message before you tell the client to disconnect.
Also you can also make use of the Last Will & Testament to have the broker publish (after the KeepAlive has expired) a message on the client's behalf if it is disconnected due to a crash/network failure.
This technique will work with any browser.

Server socket listener does not response to emit

I have a react native 0.59 app with nodejs 10.2 as backend. The socket.io 2.2.0 running on a server and it is 2.1.1 running on the app client. Here is the socket related code:
Nodejs server:
All socket.io related code is in the index.js file:
io.on('connection', (socket) => {
console.log("socket.id : ", socket.id);
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
console.log("Socketio server is initialized");
//disconnect
socket.on('disconnect', async function() {
try {
await SocketList.update({
active: false
}, {
where: {socket_id: isocket.id}
});
} catch(err) {
console.log("err in false socket id", socket.id);
}
console.log('disconnected event');
});
});
A listener for message is implemented.
React Native App:
The socket.io client used is 2.1.1. The socket is initiated in App.js and pass to Chat component. In the Chat component, connect is made with the socket to the server and emit a message:
App.js:
//socket.io
const socket = io(GLOBAL.BASE_URL, {
transports: ['websocket'],
jsonp: false
});
let props = {
eventId: "",
user: ""
};
const ChatWithSocket = (props) => (<Chat {...props} socket={socket} />)
//create the navigator
const navigator = createStackNavigator(
{
Event: Event,
Chat: {
screen: ChatWithSocket,
}
}, {
initialRouteName: "Event"
}
);
Component Chat.js:
When user enter a chat message and click send, The socket fires up the connect and emit a message with the message entered by the user:
_onSend(messages = []) {
console.log("socket.io in chat _onSend : ", this.props.socket.id);
this.props.socket.connect();
this.props.socket.on('connect', () => {
socket.emit("message", {msg: messages[0].text});
});
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
The problem is after the chat message is sent from the app, there is no response from the server and the following socket listener code is not executed:
socket.on('message', (msg) => {
console.log("msg received by server socket : ", msg);
});
Here is the console output (portion) on Nodejs server:
Listening on port 3000...
Executing (default): SELECT 1+1 AS result
DB connection has been established successfully.
socket.id : U0Vm-O5ainh-IRusAAAA
Socketio server is initialized
err in false socket id U0Vm-O5ainh-IRusAAAA
disconnected event
socket.id : 7qo9ncTog0dhPfL6AAAB
Socketio server is initialized
The initial socket connection was closed and the socket 7qo9ncTog0dhPfL6AAAB is initiated again.
Here is the app console output showing 2 messages have been sent by client 7qo9ncTog0dhPfL6AAAB which matches the socket.id on the server:
4-14 22:21:19.034 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'
04-14 22:21:24.286 26574 26634 I ReactNativeJS: 'socket.io in chat _onSend : ', '7qo9ncTog0dhPfL6AAAB'

sending messages to specific Client with node-ipc

I have an electron app where different clients communicate with a server over a Network using node-ipc.
As long as the client connects to the server first it is no problem to answer that specific client. According to the docs I have on the Server:
NodeIpc.serveNet(
function () {
NodeIpc.server.on(
'Client.message',
function (data, socket) {
NodeIpc.log('got a message from', (data.id), (data.message));
NodeIpc.server.emit(
socket,
'ServerData',
{
message: 'have some initial cofiguration data'
}
);
);
NodeIpc.server.start();
}
and on my Client:
NodeIPC.connectToNet(
'world',
function(){
NodeIPC.of.world.on(
'connect',
function(){
NodeIPC.log('## connected to world ##', NodeIPC.config.delay);
NodeIPC.of.world.emit(
'Client.message',
{
id : UniqueClientID,
message : 'Some information about myself'
}
);
});
});
That works great, but I cannot figure out how to push some additional information to a specific client some time Later. Trying
NodeIpc.server.of['UniqueClientID'].emit(
'additional Data',
{
message: 'some more configuration'
}
)
});
and
NodeIpc.server.emit(
UniqueClientID,
'additional Data',
{
message: 'some more configuration'
});
do not work.
Does anyone know how to send a message to a given client? (of course there is always the possibility to broadcast that message and let the client decide if it's for him, but I would prefer to talk to the directly)

Resources