socket.io emitting message to room does not work - node.js

Events binding for socket are moved to separate module:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
global.io.sockets.in('rooma').emit('message', data);
});
}
server.js:
var app = express();
//creating socket server
server = http.createServer(app);
io = global.io = require('socket.io').listen(server, {'log level': 3});
io.sockets.on('connection', function(socket) {
//binding events on socket
events.bind(socket, io);
});
The problem is, that message is never sent to the clients in 'rooma'. But if i emit it global:
global.io.sockets.emit('message', data);
It works. Where can be problem? I've tested the client belongs to room for sure.

this works when you get the initialisation of the event from the room to which you like to send your message:
exports.bind = function(socket) {
socket.on('join', function(data) {
socket.join(data.type);
});
socket.on('message', function(data) {
socket.get('room', function (error, room) {
io.sockets.in(room).emit('message', data);
});
});
}

Related

Why is io.sockets.in not working with my code?

Client Side script
var socket = io.connect();
var room = "abc123";
socket.on('connect', function() {
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
Server side script
io = socketio.listen(server);
io.sockets.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party
people?');
I am trying to send message to abc123 but io.sockets is not working.

socket.io client not receiving message

When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!

nodejs client server issue when reconnecting

I am very new to nodejs and I have some client-server implementation, which basically works the following manner : I submit a form which throws data to a client remote server. The latter send me back some new data.
net.createServer(function (socket) {
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
//socket.end();
});
app.post('/api/sender', function(req, res) {
socket.write(some_input);
res.end();
});
}).listen(9000);
This works well until the client disconnects itself and reconnects, then I get the following error message :
{ [Error: This socket has been ended by the other party] code: 'EPIPE' }
And the code crashes at this line socket.write(some_input). Can someone can help ?
here's how this could be tackled :
module.exports = function(app) {
var clients = {};
var server = net.createServer(function (socket) {
server.getConnections(function(err, count) {
var id = sha1(socket.remoteAddress);
clients[id] = {
stream: through(),
socket: socket,
}
clients[id].stream.pipe(socket);
});
socket.on('error',function(err){ console.error(err)});
socket.on('data', function (data) {
some_method(data)
});
socket.on('end', function() {
console.log('CONN: disconnected');
socket.end();
});
app.post('/api/sender', function(req, res) {
// here id is the IP adress got from req
if (clients[id]) {
clients[id].stream.write(input);
}
res.end();
});
}).listen(9000);
};

Socket.io emit in app doesn't work

I emit "wallet-update" with data but io doesn't react on it:
io.emit("wallet-update", total);
io.on('wallet-update', function(data){
console.log(data);
});
And when I emit events from socket in browser all is ok:
io.on('connection', function (socket) {
socket.on('connect', function() {
console.log("connect");
});
});

Issue with socket.io join room

I have a issue with socket.io with rooms.
See the server code:
This code below is working properly.
io.on('connection', function(socket){
socket.join("myroom");
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
});
But I want the user to enter the room after an event.
Like the code below.
io.on('connection', function(socket){
socket.on('chat message', function(data){
io.in("myroom").emit('chat message', data);
});
socket.on('join', function(name, device, room){
socket.join("myroom");
});
});
It's almost the same code , but does not work. What am I doing wrong?
The event is being called correctly.
Edit. Added the front-end code:
var socket = io.connect('http://localhost:5000');
$('#msg_form').submit(function(){
socket.emit('chat message', $("#m").val(), "myroom");
$('#m').val('');
return false;
});
$("#user").submit(function() {
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name, device, room);
$("#messages").focus();
}
});
Thank you.
I made this small demo to explain, I simulate the client-side event by setTimeout functions:
Server side:
var http = require('http');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(9999);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('message', function(data){
io.in("myroom").emit('message', data);
});
socket.on('join', function(name, device, room){
console.log("new client has joining a room");
socket.join("myroom");
});
});
Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:9999');
setTimeout(function () { console.log("msg emmited to server");
socket.emit('join');
},
10000);
setTimeout(function () {
console.log("msg emmited to server");
socket.emit("message","message from client");
},
20000);
socket.on("message",function(data){
console.log("message received from server ="+data);
}
);
</script>
In your $("#user").submit(...) handler, you do not prevent the default action of the form so it is likely that the page is reloaded right after you hit the submit button. And, this will reset your connection right after you hit join, giving you a newly initialize connection that is not joined into the room.
You can either add return false; to that handler or add the e argument to the handler and call e.preventDefault() to prevent the page from reloading when you hit submit.
$("#user").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var room = $("#room").val();
var device = navigator.userAgent;
if (name === "" || name.length < 2) {
$("#errors").empty();
$("#errors").append("Please enter a name");
$("#errors").show();
} else {
socket.emit("join", name);
$("#messages").focus();
}
});

Resources