How to connect socket.io to a non-website application? - node.js

I made a discord bot (with discord.js) and i want to connect it with socket.io to send and receive a message from a website.
For website I use express.
How to connect socket.io to a non-website application?

If you want to use the websocket protocol to send and receive messages from a web page, you should use the built in WebSocket class. Your code can look something like this:
const socekt = new WebSocket("ws://[INSERT YOUR SERVER ADDRESS HERE]", ["wamp"]);
socket.onopen = () => {
//code to be executed, when the websocket connection was opened
console.log("Connection made!");
}
socket.onmessage = event => {
//code to be executed, when a message is recieved.
console.log(event.data);
}
socket.onclose = event => {
//code to be executed, when the connection is closed
console.log(`Connection closed with code ${event.code}.`);
}
//function to send a message via the websocket
function sendMessage(message) {
socket.send(message);
}

Related

Socket.io listener getting skipped on the client-side while there is an emitted event

I am facing this weird issue. I am not a veteran of using Socket.io. I have been exploring this library as the app I am building needs a remote playing feature wherein players create invitations to other players so that they can use those invitations to join the game remotely. I am using React on the front end (client-side), and on the server side, I am using the Nodejs Express framework with Socket.io. I have also installed client-side Socket.io for React. The basic implementation is all working fine. When there is a new user accessing the client-side app, Server-side socket.io listens to the connection. Any events triggered by the client also get reported on the server side. I am also able to broadcast the events back to all the connected clients using the socket.broadcast.emit() method.
I am trying to store the past events (basically, these are the invitations created by the currently connected players) in an array and then emit the stored array for the new connections so that the new users will see the past events(invitations). Below is my implementation on the server side:
//Array to store previously emitted events
const activeInvites = [];
//SocketIO connections
io.on("connection", (socket) => {
console.log(`⚡: ${socket.id} user just connected!`);
//Listen to the new invites
socket.on("newInvite", (invite) => {
activeInvites.push(invite);
socket.broadcast.emit("newPrivateInvites", invite);
});
//Publish all previously created invites to the new connections
io.emit("activeInvites", activeInvites); //new connections emit this event however the client won't listen to "activeInvites" event
socket.on("disconnect", () => {
console.log(`🔥: ${socket.id} user disconnected`);
destroy();
});
function destroy() {
try {
socket.disconnect();
socket.removeAllListeners();
socket = null; //this will kill all event listeners working with socket
//set some other stuffs to NULL
} catch (ex) {
console.error("Error destroying socket listeners:", ex.message);
}
}
});
And, below is my client-side implementation:
useEffect(() => {
socket.on("activeInvites", (invite) => {
console.log(invite);
}); //a new connection client skips listening to this event. Can't understand why.
socket.on("newPrivateInvites", (invite) => {
setPrivateInvites((existingInvites) => [...existingInvites, invite]);
});
//I have commented below code. Even if I uncomment it, no difference
// return () => {
// socket.off("newPrivateInvites");
// socket.off("activeInvites");
// socket.removeAllListeners();
// };
}, [socket, privateInvites]);
//Below is the handler function I use to open up a Sweetalert2 dialog to create an invite
const createMyGameInviteHandler = () => {
swalert
.fire({
title: "New Invite",
text: "This will create a new game invite and unique joining code that you can share with your friends",
iconHtml: '<img src="/images/invite.png" />',
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yeh! Let's Go!",
customClass: {
icon: "no-border",
},
})
.then((result) => {
if (result.isConfirmed) {
player.gameId = "1234";
setMyGameInvite(player);
socket.emit("newInvite", player); //This is where I create a new invitation event
}
});
};
In the above code, the "activeInvites" event is getting skipped by the new client even after socket.io on the server side triggers a new event after the new connection is created. Note that I am using io.emit() to emit the event to all the connected clients. So, even new clients should also listen. I am not able to see where the problem is. Could you please help me with this?
I tried to store the events generated by the client and consumed by the server in the past so that I could serve those events to the new clients when they establish the connection. I was expecting that io.emit() method would emit the event that will be consumed by all the clients including the new clients. However, new clients are skipping listening to this event. I am using useEffect hook in a react component.

Message sent through socket-io getting lost after a network disconnection

So I have set up a socket connection for a chat app. Under normal circumstances where both the sender and receiver are connected to the internet, the message sent between either of them passing through my NodeJS server reach's them. But if one of them is offline and a new message is sent to them, the server will send it to the user but, since the user is offline, won't accept them at that point in time. But once the user gets back online, he should be able to accept that message. How do I make this work?
Nodejs server code
io.on("connection", (socket) => {
console.log("Connected to socket io");
socket.on('setupConnection',(userData)=>{
socket.join(userData.id);
});
socket.on("newMessage", (chatData) => {
const { message,to } = chatData;
socket.in(to).emit("newMessage", { msg: message });
});
})

Strange numbers in SocketIo events data

I'm trying to learn SocketIo in NodeJS. I'm using .on and .emit functions with same event name but server dont see incoming event emitted by client but client recive some strange numbers as data to event.
I was trying to change .on to .addListener but this is still not working.
Server:
const io = require('socket.io');
const server = io.listen(8089);
server.on('connect', socket => {
console.log('New connection!') // this line is working fine!
socket.on('ping', incomingMessage => {
console.log('Incoming message!');
socket.emit('pong', incomingMessage);
});
});
Client code:
Im using cdn from: https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js
const server = io('http://127.0.0.1:8089');
server.on('connect', () => {
server.on('pong', message => {
console.log('Incoming message! ', message);
});
server.emit('ping', 'test message');
})
But i dont see 'Incoming message' in server side terminal. Client sucessfully connected to server socket and after ~ 5 seconds i recive strange messages like:
- Incoming message! 1
- Incoming message! 3
- Incoming message! 4
in webbrowser console (using Opera)
Ok so i fixed this issue :v the problem was ping-pong event names that already was used by socket.io if i changed event names everything is working fine.

I am not able to connect to mqtt server from node.js

I am completely new to mqtt and node.js i want to get data from mqtt server at regular intervals and populate in my html5 page
Here is the sample code that am try to connect but not sure it is right way or not
var mqtt = require('mqtt');
// connect to the message server
var client = mqtt.connect('mqtt://test.mosquitto.org');
// publish 'Hello mqtt' to 'test'
client.publish('test', 'Hello mqtt');
// terminate the client
client.end()
Assuming you really are working purely with node.js you haven't given the client time to actually connect before trying to publish a message.
The node.js mqtt module README has a full example (which it appears you've copied and removed most of the important bits from). I have removed the subscription part from the demo code, but this is the bare minimum needed to publish a message.
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.on('connect', function () {
client.publish('test', 'Hello mqtt');
client.end();
});
Following code upload data on hivemq MQTT Broker at regular interval.
var mqtt = require('mqtt');
// connect to the message server
var client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', function () {
setInterval(function () { client.publish('mytopic', 'Hello mqtt') }, 1000)
})
If you want to retrieve that data then use the following function
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})

Prevent Socket connection from initializing again

I am trying to make a chat app which sends first message as "Hi. there".
But due to some some reasons (unstable internet connection might be one) the socket get initialized multiple times and sends the "Hi. there" message multiple times. Below is the code. How to stop the app for sending multiple messages?
io.socket.on('connect', function() {
/* On successfull connection to server */
console.log('Connected to server');
//Some code here
io.socket.get(url + '/userstatus/subscribe', function(resData, jwres) {
//Some code here
io.socket.on("userstatus", function(event) {
//Socket updartes
// Send Message code at this line.
}
}
});
You need to change your client side code, so that it stores state, and sends it to the server on reconnect. That way the server can give the correct response.
Something like this might work:
socket.on('connect', function() {
/* On successfull connection to server */
console.log('Connected to server');
socket.emit('state', state_object);
});

Resources