socket io doesn't work both way? - node.js

My current problem is that there are two browsers (two users). Once both of them are connected, they could do a certain socket event which is a friends Request but not both at the same time. Always need to refresh one of the user's page.
Illustratively
When a user click this button
the navbar glyphicon will be incremented by 1
Serverside event
io.on('connection', function(socket){
// Everytime user is connected, I will do some Database operation to store the socketId, it will look something like this
user.socketId = socket.id; // For simplicity.
console.log(socket.request.user.username); // is using passport-socket.io library
socket.on('friendsRequest', function(data) {
// Got these two datas from input hidden on html by using Jquery
var socketId = data.socketId;
var userId = data.userId;
socket.to(socketId).emit('friendsRequest', socket.request.user);
console.log("Successful" + " from " + socket.request.user.username);
});
The weird thing is , on the serverside it is always showing console.log("Successful" + " from " + socket.request.user.username); meaning if click the button on both User's browser it will show correctly
"Successful from UserA"
"Successful from UserB"
But the problem is on the clientside, the targeted html never changed, it always one of the browser navbar's glyphicon will be incremented
Here's the code on the client side
// This event will send the targeted data like socketId and userId back to the server
$(document).on('click', "#addFriend", function(e){
e.preventDefault();
var userId = $('#userId').val();
var socketId = $('#socketId').val();
socket.emit('friendsRequest', {
userId: userId,
socketId: socketId
});
});
// Once the server has done doing his job, this event will listen.
socket.on('friendsRequest', function(data) {
var totalRequests = parseInt($('#totalRequests').html());
console.log(totalRequests);
totalRequests += 1;
$('#totalRequests').html(totalRequests);
$('#friendsRequested').append('<li>' + data + '</li>');
});
The main problem is on the clientside socket.on('friendsRequest');
It only works of one of the browsers but not both at the same time when I fired the friendsRequest event
Need someone with socket.io expertise to explain to me why it doesn't work both ways. As to my logic it is supposed to work.
html
<input type="hidden" name="socketId" id="socketId" value="ValueOftheSocketId" />
<button type="submit" id="addFriend" class="btn btn-default">Add Friend</button>

If the event 'friendsRequest' is not fired the error always will be when you emit it on server:
socket.to(socketId).emit('friendsRequest', socket.request.user);
It is probably that the socketId is not the correct, why? :
The socket.id is reset when a reconnection occurs. So that probably would cause that when you do: socket.to(socketId).emit('friendsRequest', socket.request.user);
it is sent anyone.
A reconnection can happen when a error occurs inside a event listener on client (it will not appear on console).
So for watch if that happens you can use the default event 'disconnect' on server:
socket.on('disconnect', function () {
console.log('user disconnected');
});

Related

Websockets & NodeJS - Changing Browser Tabs & Sessions

I've started writing a node.js websocket solution using socket.io.
The browsers connects to the node server successfully and I get see the socket.id and all config associated with console.log(socket). I also pass a userid back with the initial connection and can see this on the server side to.
Question: I'm not sure the best way to associate a user with a connection. I can see the socket.id changes every page change and when a tab is opened up. How can I track a user and send 'a message' to all required sockets. (Could be one page or could be 3 tabs etc).
I tried to have a look at 'express-socket.io-session' but I'm unsure how to code for it and this situation.
Question: I have 'io' and 'app' variables below. Is it possible to use the 2 together? app.use(io);
Essentially I want to be able to track users (I guess by session - but unsure of how to handle different socket id's for tabs etc) and know how to reply to user or one or more sockets.
thankyou
The best way to handle the situation is rely on SocketIO's rooms. Name the room after the user's unique ID. This will support multiple connections out of the box. Then, whenever you need to communicate with a particular user, simply call the message function and pass in their id, the event, and any relevant data. You don't need to worry about explicitly leaving a room, SocketIO does that for you whenever their session times out or they close their browser tab. (We do explicitly leave a room whenever they log out though obviously)
On the server:
var express = require('express');
var socketio = require('socket.io');
var app = express();
var server = http.createServer(app);
var io = socketio(server);
io.on('connect', function (socket) {
socket.on('userConnected', socket.join); // Client sends userId
socket.on('userDisconnected', socket.leave); // Cliend sends userId
});
// Export this function to be used throughout the server
function message (userId, event, data) {
io.sockets.to(userId).emit(event, data);
}
On the client:
var socket = io('http://localhost:9000'); // Server endpoint
socket.on('connect', connectUser);
socket.on('message', function (data) {
console.log(data);
});
// Call whenever a user logs in or is already authenticated
function connectUser () {
var userId = ... // Retrieve userId somehow
if (!userId) return;
socket.emit('userConnected', userId);
}
// Call whenever a user disconnects
function disconnectUser () {
var userId = ... // Retrieve userId somehow
if (!userId) return;
socket.emit('userDisconnected', userId);
}

Reconnect socket in disconnect event

I am trying to reconnecct the socket after the disconnect event is fired with same socket.id here is my socket config
var http = require('http').Server(app);
var io = require('socket.io')(http);
var connect_clients = [] //here would be the list of socket.id of connected users
http.listen(3000, function () {
console.log('listening on *:3000');
});
So on disconnect event i want to reconnect the disconnected user with same socket.id if possible
socket.on('disconnect',function(){
var disconnect_id = socket.id; //i want reconnect the users here
});
By default, Socket.IO does not have a server-side logic for reconnecting. Which means each time a client wants to connect, a new socket object is created, thus it has a new id. It's up to you to implement reconnection.
In order to do so, you will need a way to store something for this user. If you have any kind of authentication (passport for example) - using socket.request you will have the initial HTTP request fired before the upgrade happened. So from there, you can have all kind of cookies and data already stored.
If you don't want to store anything in cookies, the easiest thing to do is send back to client specific information about himself, on connect. Then, when user tries to reconnect, send this information again. Something like:
var client2socket = {};
io.on('connect', function(socket) {
var uid = Math.random(); // some really unique id :)
client2socket[uid] = socket;
socket.on('authenticate', function(userID) {
delete client2socket[uid]; // remove the "new" socket
client2socket[userID] = socket; // replace "old" socket
});
});
Keep in mind this is just a sample and you need to implement something a little bit better :) Maybe send the information as a request param, or store it another way - whatever works for you.

Chat App using Socket.io and Node.js

I am developing chat app using Node.js and Socket.io.
Here is my code.|
socket.js
var io = require('socket.io').listen(8001);
var http = require('http');
var url = require('url');
var fs = require('fs');
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat Message By: ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Hello " + name + '!',
msgr : "Mr.Server"
});
});
});
});
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8001');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('Sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
$("#btnSubmit").click(function(){
alert("Disconnected");
//socket.clients[kickedUserSocketId].onDisconnect();
socket.close();
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
socket.emit('forceDisconnect');
</script>
</head>
<body>
<input type="text" id="msg"></input>
<button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
<input id = "btnSubmit" type="submit" value="Disconnect"/>
</html>
I am running first socket.js from command prompt. After that, I am running .html file in browser 2 times. Now 2 users can chat via browsers. But when I am trying to put my .js file and .html file on server which I have created using FileZila and running .js file, it is running but when I am trying to run .html file on server side(In this case FileZila) , by giving the IP address and Port number of server it is not running. Can you tell me what is the problem?
This doesn't seem to be a nodejs-issue.
You have a server that should be reachable by IP with something like 'http://your.domain.or.ip:80'.
If you get a "can't connect" in your browser then make sure there is no firewall in its way and that port (in the example: 80) is reachable from your browser location (aka known as "your pc"). Please note that you have your socket-service on port 8001 and your web server maybe runs on a different port? Make sure both ports are open.
If you get a blank page, check the browser javascript error messages.
There is a chance that you forgot to upload the file 'socket.io.js' in that directory '/socket.io/'. Try to download that file directly to see if your server serves.

socket.io get data from onclick action then pass the data to other pages to execute the data

I want to create a page using node.js and socket.io.
There are two buttons inside the page, when I click one of them, it will change a variable which defines the animation-duration(I omit the CSS animation codes here).
When I open the same page on another web-browser and click one of the buttons, I hope to see the change in both of the webpages. I don't know how to write the code inside the socket.on('chat', function(data){???}); to make two pages communicate with each other.
Client side:
//socket.io codes--
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('chat', function (data)
{
function change_position(data)
{
document.getElementById("animation1").style.WebkitAnimationDuration=data;
}
});
</script>
.....
//action--
<body>
<button id="1b" type="button" style="position:absolute; left:377px; top:220px;" value="2s"; onclick="change_position(value)"> - 1 - </button>
<button id="2b" type="button" style="position:absolute; left:477px; top:220px;" value="15s"; onclick="change_position(value)"> - 2 - </button>
</body>
server side:
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
chat_room.sockets.emit('chat', data);
});
});
If your want a message to propagate to all clients/sockets, in your server you should have something like:
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
socket.emit('chat',data);
});
});
The line socket.emit('chat',data); allows you to send the message back also to the sender of it, because broadcast will send it all other sockets.
Of course, you could ommit that line and handle the message sending logic in the client; i.e. adding some JavaScript code that makes the changes you want just after sending the message to the server.
You can emit on your client using socket.emit('message', data). Then on the server get it with chat_room.socket.on('message', data). Emit it to the clients using chat_room.sockets.emit('message', data).

Sending message to specific client with socket.io and empty message queue

I´m going crazy with socket.io!
Documentation is so bad it's simply not true.
I want to send a feedback to specific client over socket.io
My server side looks like this:
app.get('/upload', requiresLogin, function(request, response) {
response.render('upload/index.jade');
io.sockets.on('connection', function (socket) {
console.log('SOCKET ID ' + socket.id);
io.sockets.socket(socket.id).emit('new', 'hello');
});
});
and the client side looks like this:
$(document).ready(function() {
var socket = io.connect('http://localhost:80/socket.io/socket.io.js');
socket.on('new', function (data) {
console.log(socket.id);
console.log(data);
//$('#state').html(data.status);
});
});
but the client does simply nothing. I have tried nearly everything. Can someone tell me what I am doing wrong, please! :(
to send a message to a specific client save every one that connects to the server in an Object.
var socketio = require('socket.io');
var clients = {};
var io = socketio.listen(app);
io.sockets.on('connection', function (socket) {
clients[socket.id] = socket;
});
then you can later do something like this:
var socket = clients[sId];
socket.emit('show', {});
A couple of ways to send feedback to a specific client over socket.io include:
As stated by pkyeck, save all clients to an Object, so you can send to these specific clients later in your route handlers, e.g.:
var sessionsConnections = {};
sio.on('connection', function (socket) {
// do all the session stuff
sessionsConnections[socket.handshake.sessionID] = socket;
});
or, use socket.io's built in support for rooms - subscribe each client to a room on connection and send via this room within route handlers, e.g.:
sio.on('connection', function (socket) {
// do all the session stuff
socket.join(socket.handshake.sessionID);
// socket.io will leave the room upon disconnect
});
app.get('/', function (req, res) {
sio.sockets.in(req.sessionID).send('Man, good to see you back!');
});
Acknowledgement:
http://www.danielbaulig.de/socket-ioexpress/#comment-1158
Note that both these example solutions assume that socket.io and express have been configured to use the same session store and hence refer to the same session objects. See the links above and below for more details on achieving this:
https://github.com/LearnBoost/socket.io/wiki/Authorizing
2 things
1) You should really place your io.sockets.on(..) outside your app/update route to prevent adding multiple listeners for clients.
2) io.sockets.socket(id); should not be used, it should have been socket.emit('new', 'hello')
In socket.io 1.0, this is how it would work. It may work for lower versions, but I cannot guarantee it.
socket.to(socket_id_here).emit('new', 'hello');
This works because socket.io automatically adds a socket to a room with the socket's id on connection.
Also, if you plan to upgrade to version 1.0, there are a lot of changes to the api, so you'll sometimes have to change some code to make it work in 1.0.
The correct way to do this in Socket.io 1.0+ is:
io.to(users_socket_id).emit('new', 'hello');
You can also substitute a room name for 'users_socket_id' to emit to a specific socket.io room.
First of all, you cannot use socket.id on client side.
And then change the line
var socket = io.connect('http://localhost:80/socket.io/socket.io.js');
to
var socket = io.connect('http://localhost:80/');
I believe io.sockets.socket has been removed and has been a problem in Socket.IO (https://github.com/socketio/socket.io/issues/1618).
You can use io.sockets.connected[socket.id] and store the socket.id to reference with the user via username:
var usernames = {};
usernames[username] = socket.id;
// Sending the message
io.sockets.connected[usernames[username]].emit(...);
I don't see it anywhere on the documentation so I can see how this hasn't been answered. Also, if you don't have any reference via usernames, you can instead try:
users[socket.id] = socket.id;
to duplicate the key and value for easy access.
There is also possibly another way by using io.clients as described below, but I haven't used that method.
OTHER SOLUTION: Send message to specific client with socket.io and node.js
Have you tried using?
var socket = io.connect('http://localhost:80/');
i tired with the latest version of node and socket.io
below i am going to post complete code
<ul id="messages"></ul>
<form action="">
<input id="id1" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var io = io.connect();
$('form').submit(function(){
io.emit('drumevent', $('#id1').val());
$('#id1').val('');
return false;
});
io.on('drumevent', function(msg){
console.log(msg);
$('#messages').append($('<li></li>').text(msg.message+' quantity = '+msg.quantity));
});
</script>
server side code
var usernames = {};io.on('connection', function(socket){usernames["username"] = socket.id;
socket.on('drumevent', function(msg){
var socketId = socket.id;io.to(socketId).emit('drumevent', data);

Resources