Strange numbers in SocketIo events data - node.js

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.

Related

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

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);
}

How to close a Node.js UDP (dgram) socket

The App crashes if I do not call client.close in the program below.
The send of message and receiving of data works fine. But if I exit the function and comes back to it again later, the App crashes and I can not receive message anymore. I restart the Smart Phone and it works again only for the first time the function runs.
If I put client.close() inside the client.on('message',, I only get the first data from the host or source, because the socket will close prematurely. Also the App do not crash.
If I remove the client.close(), I get all the data from multiple sources saved in the array I provided let RawMessageUDP = [].
Also I confirmed that the callback function of the client.on('message', will not be executed when there are no more message in the socket.
How can I determine that there are no more message in the socket, so I can close it?
There are two hosts which receives the message and reply data string back to this App. There are no issues in the host I confirmed since they close the connection after sending.
Send_UDP_Multicast = async () => {
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
let RawMessageUDP = []
let countMessage = 0
client.on('error', (err) => {
console.log(err.stack)
client.close()
})
client.on('message', (data, rinfo) => { //Console: socket-x, bound to address: 0.0.0.0, port: 65000 max
RawMessageUDP[countMessage] = data.toString()
console.log('Receiving remote data.' + RawMessageUDP[countMessage])
countMessage++
//client.close()
})
client.send(message, 0, message.length, 1900, '239.255.255.250', (err) => {
if (err) {
console.log(err);
client.close();
}
})
}
https://github.com/jurniores/SocketUDP resolve your problem. This lib you will find how to disconnect the clients and if the clients fall down it will disconnect them and will not overload your server.

Mosca sends multiple messages continously

I have setup a node js server with Mosca running on it. Clients are able to connect to the Mosca server and publish a message. I need to the send an acknowledgment in the form of a message(subscribed to some topic) back to the client.
The below code sends multiple messages continuously once the message is published by the client. Am I missing anything?
var settings = {
port: 1882,
backend: ascoltatore
};
var message = {
topic: 'crofters',
payload: 'OK', // or a Buffer
qos: 2
};
var server = new mosca.Server(settings);
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client ) {
var packet_payload = packet.payload;
packet_payload = packet_payload.toString();
console.log('Published', packet_payload);
server.publish(message, function() {
console.log('done!');
});
});
server.on('ready', setup);
function setup() {
console.log('Mosca server is up and running');
}
The event listener server.on('published', function(packet, client){...} listens to every publishing events, including the server's.
What is happening is that when you use server.publish(message, function(){...}) inside that listener it triggers another published event, which is immediately caught by the listener.
It never stops publishing because it never stops catching its own events.
I have been facing similar issues. If you notice, Mosca has only QoS 0 and Qos 1
So I suppose the broker tries to send the same message more than once "at least once" until it receives some acknowledgement from a client. Check this document out

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()
})

nodejs socket.io - connected to server but emit doesn't do anything

I'm starting to work with Socket.io and my nodeJS API
I succeeded to get my user connected, and showed a message on my server.
But now, I'm trying to send data to my client -> then server -> then client again etc.
But when I use emit nothing appends... So this i my code :
SERVER SIDE
io.on('connection', function(socket){
console.log("user connected") // I see that
socket.emit('text', 'it works!'); //
socket.on('test1', function (data) {
console.log('received 1 : '); // Never showed
console.log(data); // Never showed
});
}
CLIENT SIDE
var socket = io.connect(myUrl); // good connection
socket.emit ('test1', {map: 4, coords: '0.0'}); // never showed on the server side
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
Any ideas?
thanks !
Your Starter Code seems to be valid, you need to check two things :
if you successfully included the socket.min.js in the client side
if you re having any error printed in the console
On the client side, you have to wait until the connection succeeds before it is safe to send data to the server. Connecting to the server is not synchronous or instantaneous (thus it is not ready immediately). You are trying to send data before the connection is ready.
Put your first send of data inside a socket.on('connect', ...) handler.
var socket = io.connect(myUrl); // good connection
// send some data as soon as we are connected
socket.on('connect', function() {
socket.emit ('test1', {map: 4, coords: '0.0'});
});
socket.on('text', function(text) {
alert(text); // never showed
socket.emit('test', { "test": "test2" });
});
this worked for me
CLIENT SIDE
//sending custom data to server after successful connection
socket.on('connect', function(){
this.socket.emit('client-to-server', {map: 4, coords: '0.0'});
});
//listening the event fired by the socket server
socket.on('server-to-client', function(dataSendbyTheServer){
// do whatever you want
console.log(dataSendbyTheServer);
});
SERVER SIDE
io.on('connection', function(socket) {
// listening the event fired by the client
socket.on('client-to-server', function (data) {
console.log('received 1 : ');
// sending back to client
io.emit('server-to-client', data)
});
});

Resources