I have a problem with socket.io from nodeJs.
I am trying to create a connection from a client to a server. Once the client is connected, the server sends a message to the client (ack).
Until then, everything works fine but when I disconnect the server and restart it, it sends me the message twice to the client.
If I repeat the manipulation a third time, three messages will appear.
I have captured the problem:
client.js
var socket = require('socket.io-client')('http://localhost:8050', {
'forceNew':true
});
socket.on('connect', onConnect);
function onConnect(){
console.log('connect ' + socket.id);
socket.emit('sendConnect','First connect');
socket.on("ack", function(data) {
console.log("ack reçu");
});
socket.on('disconnect', function(reason) {
console.log(reason);
});
}
server.js
var io = require("socket.io");
var sockets = io.listen(8050);
sockets.on('connection', function (socket) {
socket.on('sendConnect', function (data) {
console.log("message :" + data);
socket.emit('ack');
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});
});
I looked if this bug was already arriving without finding an answer.
I must surely be doing something wrong!
Thank you in advance for your help.
Your onConnect function adds new event listeners each time the socket connects. Move the event subscriptions out of onConnect like this:
var socket = require('socket.io-client')('http://localhost:8050', {
forceNew: true
});
socket.on('connect', onConnect);
socket.on('ack', function(data) {
console.log('ack reçu');
});
socket.on('disconnect', function(reason) {
console.log(reason);
});
function onConnect() {
console.log('connect ' + socket.id);
socket.emit('sendConnect', 'First connect');
}
Related
So i'm building an vscode extension in typescript and node and i have a python app which sends data with socket to localhost 8080 and im catching it like this :
export default async function getSock(port, adress, dataOld): Promise<void> {
let server = net.createServer(function (socket) {
socket.setEncoding('binary');
socket.on('data', async function (data) {
console.log('client send:' + data);
let m = port
new **UI**(data);
server.close()
});
socket.on('error', function (exception) {
console.log('socket error:' + exception);
socket.end();
});
socket.on('close', function (data) {
console.log('client close:' + data);
});
socket.on('end', function() {
console.log('disconnected from server');
server.close()
});
})
server.listen({port: port, adress: adress});
}
Now i need some mechanism that if listening for 5 seconds and no data passed from the socket, i stop listening and call "new UI(dataOld)"
Currently I am trying this way:
io.sockets.on('connection', function (client) {
console.log("client connected: " + client.id);
io.sockets.socket(client.id).emit("connected", client.id);
client.on("sendMessage", function (data) {
//send message code
});
});
What i want sendMessage code should be in separate file. So how to do ?
What i have tried :
//in first.js:
var events = require('events');
var em = new events.EventEmitter();
var msg = require('./message.js');
var emitter = msg.em;
io.sockets.on('connection', function (client) {
console.log("client connected: " + client.id);
io.sockets.socket(client.id).emit("connected", client.id);
emitter.emit('sendMessage');
});
//in message.js
client.on("sendMessage", function (data) {
//return "Hello";
//perform db operation
});
whether it is correct or wrong ? Can anyone help?
or is there any new correct way to do ?
You can put the handler in some other file and export it.
Main code:
const sendMessage = require('./send-message');
io.sockets.on('connection', function (client) {
console.log("client connected: " + client.id);
io.sockets.socket(client.id).emit("connected", client.id);
client.on("sendMessage", sendMessage);
});
send-message.js:
module.exports = function (data) {
//send message code
});
Socket.io how to handle client internet disconnect event?
I read heartbeat on stackoverflow but that solution does not work for me.
I found a ping solution but I think it is a bad approach to ping all the connected user, it will slow down the server
here is my code, kindly guide how to handle internet disconnect event?
io.on('connection', function(client) {
client.on('online', function(data) {
socket_api.user_online(data.user_id, function (err,res){
if (err) {
client.emit ('error',err);
} else {
console.log ("client connected")
client.emit ('online_response', res);
}
});
// client.emit('messages', 'Hello from server');
});
client.on('disconnect', function (data){
console.log ("Client disconnected");
});
});
// use this on server side
function sendHeartbeat(){
setTimeout(sendHeartbeat, 8000);
io.sockets.emit('ping', { beat : 1 });
}
io.sockets.on('connection', function (socket) {
socket.on('pong', function(data){
console.log("Pong received from client");
});
}
setTimeout(sendHeartbeat, 8000);
.................................................
// on Client side
socket.on('ping', function(data){
socket.emit('pong', {beat: 1});
});
hope this help you
I'm a new in nodejs, i have project about TCP server client , I init 2000 client and send to server 1KB/1s on terminal, after i click X button on terminal (disconnect client unusual).
On my server, only 1500-1600 client disconnect, the rest client still not disconnect ??
So how can i clean this garbage connection ??
How can i check status of socket ??
Client code :
var test = setInterval(function () {
var client = socks.connect(function (socket) {
lstClient.push(socket);
var message = '';
console.log('>> Connection successful');
socket.on('data', function (data) {
console.log(data.length);
});
var myTimer = setInterval(function () {
if (socket.writable) socket.write(datareal.toString());
else clearInterval(myTimer);
}, 5000);
socket.on('error', function (err) {
console.log(err);
});
socket.on('close', function () {
console.log('Disconnect socket...');
socket.destroy();
});
})
}, 15);
Thanks to advance !!
I'm sending data to all clients but I need to send the data only one client (who make request) too.
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
......
});
}
There is a function called io.sockets.emit but there is no io.socket.emit.
I assume that in the post method you have identified the user or session.
So you can create a room per user to later emit on it.
client.js
var room = "#usernameRoom";
socket.on('connect', function() {
socket.emit('privateroom', room);
});
socket.on('privatemessage', function(data) {
console.log('Incoming private message:', data);
});
server.js
io.sockets.on('connection', function(socket) {
var socket_room;
socket.on('privateroom', function(room) {
socket_room = room;
socket.join(room);
});
socket.on('disconnect', function() {
if (socket_room) {
socket.leave(socket_room);
}
});
});
app.post(.....){
myModel.save(function (err) {
if (err) return handleError(err);
///send to all
io.sockets.emit("ev", { ...... });
//// send to one client
// now, it's easy to send a message to just the clients in a given private room
privateRoom = "#usernameRoom";
io.sockets.in(privateRoom ).emit('privatemessage', 'Never reveal your identity!');
});
}
hope that helps