( Socket.io ) One socket connection multiple rooms - javascript

I'm having problems with socket.io.
I try to create a single socket connection where this is connected to multiple rooms.
This is my current code:
function JoinRoom(id){
socket = io(domain);
  socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
The problem is that if I remove the var socket.io(domain) function was not connected and do not receive data from the room.
Example:
socket = io(domain);
function JoinRoom(id){
  socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
If I take the socket.io() function of the JoinRoom() function I do not receive messages message or anything. It does not work.
What am I doing wrong? Any solution?

On the client, create an event to indicate the access room.
On the server, apply the access logic.
Client
var socket = io('http://localhost');
function JoinRoom(data){
socket.emit("join", data);
}
var data = {
room:'ejemplo'
};
JoinRoom(data);
Server
var io = require('socket.io')(app);
io.on('connection', function(socket){
socket.on('join', function(data){
console.log(data); // data = { room: String, ...}
socket.join(data.room);
});
socket.on('leave', function(data){
socket.leave(data.room);
});

Related

TCP socket server in node js with persistent connection

I have created one socket server in node js where I can send some data and receive from the server, but the problem is every time connection is closing and creating new PID for another request. here my requirement is once my IOT device connects to the server then the connection should stay there and I want to send, receive data any time.
Can anyone help me out?
I am posting my code below
Server code
var net = require('net');
// Create Server instance
var server = net.createServer(main);
server.listen(9010, function() {
console.log('server listening on %j', server.address());
});
function main(sock) {
sock.setEncoding("utf8");
sock.on('data', function(data) {
var data = data;
console.log('Request data is ', data);
console.log('Says:', data);
sock.write("responding to client");
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection closed');
});
sock.on('error', function (err) {
console.log('Connection error: %s', err.message);
});
};
Client code
var net = require('net');
//params
var HOST = 'myhost';
var PORT = 9010;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello socket server');
});
client.on('data', function(data) {
console.log('Recieved data: ' + data);
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});

Socket.io rooms is sending to everybody, not just single room

I have no idea why this won't work; here's my code:
io.on('connection', function(socket) {
socket.on('join', function(data) {
socket.join(data.email); // We are using room of socket io
User.findById(bid.highestBidder, (err, theUser) => {
io.sockets.in(theUser.email).emit('outbid', {msg: 'You have been outbid!'});
});
});
});
Now, here's the code on the client-side javascript:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var userEmail = $("#userEmail").val();
socket.emit('join', {
email: userEmail
});
socket.on("outbid", function(data) {
console.log(data);
});
</script>
If you need me to paste more code, let me know and I will.
Basically, when the socket function gets executed, it's sending it to every browser instead of just the room with the "email."
io.on('connection', function(socket){
socket.join('room name');
});
io.to('room name').emit('some event');

(Node js) How to send notification to specific user?

i have code for server
server.js
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
var nik = {};
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
socket.on( 'new_count_message', function( data ) {
io.sockets.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
});
socket.on( 'update_count_message', function( data ) {
io.sockets.emit( 'update_count_message', {
update_count_message: data.update_count_message
});
});
});
and this is how i use that
$.ajax({
type: "POST",
url: "(some_url)",
data: $("id_form").serialize(),
dataType: "json",
beforeSend:function(){
alert('bla..bla..');
},
success: function (result) {
if (result.status) {
var socket = io.connect('http://' + window.location.hostname + ':3000');
socket.emit('new_count_message', {
new_count_message: result.new_count_message
});
} else if (result.status == false) {
alert(error);
return false;
}
},
error: function(xhr, Status, error) {
alert(error);
}
});
that function is working perfectly, but it send to all. how to send notif to specific user? i have the ID user that i want to send the notif
Thanks
Well,
With io.sockets.emit you emit a message to all sockets. Instead use io.sockets.in("roomname").emit("message").
As well if you have the socket ID where you want to send the message you can use io.sockets.connected["socketid"].emit("message").
If you are inside the io.on('connection') function and you want to send a message to the same socket you can simply use socket.emit.
Another way is:
When a new socket connects, add this socket to a specific room socket.join("UniqueUserId") or socket.join("UniqueUserSessionId") ... Then use the 1st option io.sockets.in("UniqueUserId").emit("message") or io.sockets.in("UniqueUserSessionId").emit("message")
Examples:
io.on('connection', function (socket) {
//get the unique socket socketId on connection
var socketId = socket.id;
//you can add this socket id to a Database to use it later, etc...
//use sessionStore like Redis or memStore to get a unique sessionId
//as well you can extract a cookie with the UserId (you need to secure this to be sure that the user not modified the cookie) (you can use 2 cookies 1 for the userid other for the encrypted password and check if the cookies data is the same than in your users Database) etc etc etc. User Session is a lot better). Read about nodejs session store and socket session. Something like...
var cookies = qs.parse(socket.handshake.headers.cookie, "; ");
var user_id = cookies.user_id; //or some other cookie name;
socket.join(user_id);
socket.on( 'new_count_message', function( data ) {
//all sockets
io.sockets.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//same Socket
socket.emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//specific Socket by SocketId
//io.sockets.connected["socketid"].emit( 'new_count_message', {
io.sockets.connected[socketId].emit( 'new_count_message', {
new_count_message: data.new_count_message
});
//all sockets in a specific Room
//io.sockets.in("roomname").emit( 'new_count_message', {
io.sockets.in(user_id).emit( 'new_count_message', {
new_count_message: data.new_count_message
});
});
});

How I can get a socket.username ? (socket.io)

I want to write a simple chat for practical experience.
All right, but I can't get a socket.nickname for notice a join/leave from the room. (when I tried pass its, he always sad a 'undefined').
Now all right, tried to create list of rooms
UPDATE CODE:
client.js:
$('#roomForm').submit(function() {
socket.emit('createRoom', $('#roomName').val());
$('#roomForm').hide();
$('#chatForm').show();
return false;
});
socket.on('message', function(data) {
newMessage(data);
});
socket.on('showRooms', function(rooms) {
console.log(rooms);
for(var i = 0; i < rooms.length; i++) {
$('#rooms').append($('<li>')
.append($('<form id="freeRoom">')
.append($('<span id="room">').text(rooms[i] + ' ///'))
.append($('<button>').text('connect'))));
};
});
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
server.js:
io.on('connection', function(socket) {
socket.on('sendNickname', function(username) {
socket.username = username;
users.push(socket.username);
socket.emit('showRooms', rooms);
});
socket.on('disconnect', function() {
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has left the room');
users.splice(users.indexOf(socket.username), 1);
socket.emit('showRooms', rooms);
});
socket.on('message', function(data) {
socket.broadcast.to(socket.room).emit('message', data);
});
socket.on('createRoom', function(room) {
socket.leave(socket.room);
socket.room = room;
rooms.push(socket.room);
socket.join(socket.room);
socket.emit('showRooms', rooms);
console.log('Rooms: ' + rooms);
socket.broadcast.to(socket.room).emit('notice', socket.username + ' has joined to room');
});
socket.on('connectToRoom', function(room) {
console.log('Will connect to that room: ' + room);
socket.join(room);
});
});
**UPD 2: **
Tried to connect free created room:
$('#freeRoom').submit(function() {
socket.emit('connectToRoom', $('#room').text());
return false;
});
P.S. And... Sorry for my english >.<
The event name that you emit, that is 'connect' is reserved in Socket.io along with 'message' and 'disconnect':
http://socket.io/docs/#sending-and-receiving-events
Socket.IO allows you to emit and receive custom events. Besides
connect, message and disconnect, you can emit custom events:
...
Change it to something else, e.g:
Server.js:
io.on('connection', function(socket) {
socket.on('send-nickname', function(nickname) {
socket.nickname = nickname;
users.push(socket.nickname);
console.log(users);
});
...
Client.js
socket.emit('send-nickname', nickname);

Can't send message to all sockets (socket.io)

Heya I'm trying to build a small chat client to learn how websockets work in order to make a game in canvas. It works great with sending sockets but they are only sending it to the the one who wrote it.
I guess I've missed something small, but I can't understand why it won't work.
Server side code
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage(data.message);
});
});
var sendMessage = function(message) {
io.sockets.emit('server-message', {message: message});
}
Client side code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('server-message', function (data) {
var history = $('#chatbox').val();
$('#chatbox').val(history + "\n" + data.message)
});
$("#write").keyup(function(event){
if(event.keyCode == 13){
socket.emit('user-message', {message: $(this).val()});
$(this).val('');
}
});
</script>
You can use socket.broadcast.emit to send a message to all other sockets.
io.sockets.on('connection', function (socket) {
socket.on('user-message', function (data) {
console.log(data);
sendMessage.call(socket, data.message);
});
});
var sendMessage = function(message) {
this.emit('server-message', {message: message});
this.broadcast.emit('server-message', {message: message});
}

Categories

Resources