When actually socket is connected in socket.io? - javascript

I'm trying to understand, when socket is connected in socket.io. I'm using express and jade. To find out, I have something like this in my server.js file:
io.sockets.on('connection', function(socket) {
console.log('Socket is connected: ' + socket.id)
This message appears each time, when I open localhost in browser, and it's ok, as I understand - each opening localhost creates new connecting - new socket.
But sometimes localhost is not open and when I start my server in node, I get this message what makes me confused. Why is this happening ?
Second strange thing, I load my views via ajax :
socket.on('connect', function() {
socket.on('loadRooms', function(data) {
var active_users = data.active_users,
socket_id = data.socket_id;
$.ajax({
url: 'rooms'
}).done(function(data_view) {
$('body').html(data_view);
console.log(data.active_users);
});
and I also don't understand why after this I get another message in my console with new socket, seeing that I don't refresh my browser... Anyone could explain me that ?

Related

Is it possible to create a "fake" socket connection to a nodejs server that is secured through SSL?

I'm using socket.io-client to create a socket connection to my locally-running server. See my code below:
// Working example of connecting to a local server that is not SSL protected
var io = require('socket.io-client')
var socket = io.connect('http://localhost:3000', {reconnect: true});
socket.on('connect', function(){ console.log("inside 'connect'") } );
socket.on('connection', function(){ console.log("inside 'connection'") } );
socket.on('event', function(data){ console.log("inside 'event'") } );
socket.on('disconnect', function(){ console.log("inside 'disconnect'") } );
var payload = {email: 'fake#gmail.com', password: 'tester'};
var tokens = {browserId: 'b965e554-b4d2-5d53-fd69-b2ca5483537a'};
socket.emit("publish", {logic:"user", method:"signIn"}, payload, tokens, function(err, creds) {
console.log("inside the socket client emit callback. err: " + err);
console.log("creds: " + creds);
});
Now for my problem. As I stated in the comment at the top of that code, I can connect to my local nodejs server and get the response I expect when I turn off SSL encryption on my server. As soon as I turn SSL on, I stop getting any response at all from the code above. I don't see any message in my server logs or from the command line, where I'm running the code above with node.
My goal is to be able to run the code above, with SSL turned on in my server, and get the same response that I get when SSL is turned off. I've tried a bunch of variations on the code I included above, such as:
connecting to "https://localhost:3000"
connecting to "//localhost:3000"
connecting to "https://localhost:3443" (this is the port I have to connect to when I have the nodejs server running with SSL)
changing {reconnect:true} to {reconnect:true,secure:true}
I'm truly stumped, and I've been doing a bunch of research on the web and on my node server. It's my company's code and I didn't originally implement the SSL components, so I've spent a few hours looking at our code and trying to understand how adding SSL changes everything. I'm also a student and have about 2 years of experience behind me, so I'm good but I'm no expert. Have I said anything above that indicates if my task is impossible to achieve, or if maybe I have just overlooked something? Any leads on things to check out would be appreciated :)

Emit Events To Socket.IO Not Working From Server

i am trying to get a chat program to work using socket.io but it doesnt seem to work properly.
i am using a Node.js server and it seems to be running properly. i think this may have something to do with emitting to rooms.
the code i have on the client browser is:
<script>
var socket = io("https://localhost:3000/userChat");
socket.on('connect', function(){
socket.emit('initialiseConnection', "user1");
});
socket.on('messageIn', function(msg){
console.log(msg);
$('#messages').append($('<li>').text(msg.message));
});
</script>
so when the page loads, socket.io it connects to the server and emits the "initialiseConnection" event on the server with "user1". which is a new room specifically for that user.
on the server, the code i have handling "initialiseConnection" is:
socket.on("initialiseConnection", function(username){
socket.join(username);
console.log(username + " has joined.");
Message.find({recipient:username}, function (err, message){
console.log("messages for "+username+": "+message.length);
for (var x = 0; x < message.length; x++){
console.log(username+"'s message "+x);
console.log(message[x]);
socket.to(username).emit("messageIn", {"message":message[x]});
}
});
});
this code as you can see, creates and joins a room with the same name as the username. the looks in the database for any messages, and tries to emit those messages to the user. i log the message. there is definately a message and the username in the "socket.to()" method is also correctly shown in the logs. but the "socket.on('messageIn')" on the client browser doesnt seem to be picking up the event.
i have also tried putting:
setTimeout(function() {
socket.to(username).emit("messageIn", {"message":"test message"});
}, 5000);
immediately after the socket.join(), in case this was related to some backbround processing that needed to complete
can anyone see where i may have gone wrong on this?
Thanks.
--EDIT 1--------------------------------------
var https = require('https');
var express = require('express');
var app = express();
var server = https.createServer(https_options, app).listen(3000);
var io = require('socket.io')(server);
var userChat = io.of("/userChat");
userChat.on('connection', function(socket){
console.log('a user connected');
socket.on("initialiseConnection", function(username){
...
});
socket.on('disconnect', function(){
socket.leave(socket.room);
});
});
You need to change this:
socket.to(username).emit("messageIn", {"message":message[x]});
to this:
socket.emit("messageIn", {"message":message[x]});
A socket is the endpoint. When sending, you just send directly to the socket. You don't send to a user in a room? You just send to a socket. Since you already have the socket in your socket variable, that's what you send to.

Can't send message to only one specific room through node.js and socket.io

I have a problem that i don't seems to be able to solve it. I'm doing some kind of integration with remote system and my code is in iframe but that can't be important for this one i hope :).
I'm trying to send a message from server to specific room/client to begin session. First thing I do is when user log in, I emit message from client side with username.
CLIENT.JS
conn.on('connect', function () {
conn.emit('session', { username: 'some_username' });
}, false);
And on server side i get message and join socket to the room.
SERVER.JS
socket.on('session', function(session) {
socket.join(session.username);
});
I have another module that communicates with this server.js script through redis. So i have two more events in server.js
SERVER.JS
var userCreate = redis.createClient();
userCreate.subscribe("userCreate", "userCreate");
var userDestroy = redis.createClient();
userDestroy.subscribe("userDestroy", "userDestroy");
userCreate.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('beginSession', data);
});
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('endSession', data);
socket.leave(JSON.parse(data).username);
});
But when ever i try to emit message from server to client i broadcast message to everyone. What am I doing wrong?
Well, from the syntax point of view you are doing everything correct.
Didn't you forget to specify the userId property in the endSession?
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).userId).emit('endSession', data);
socket.leave(JSON.parse(data).userId);
});
If that doesn't work - you should provide the contents of a data object

Socket.io with Heroku

This works perfectly on my own computers server
var socket = io.connect('http://localhost:3000');
socket.of(userid).on('email', function (data) {
console.log("here")
});
however when I switch to heroku like
var socket = io.connect('http://staginggorkemnutrition.herokuapp.com');
socket.of(userid).on('email', function (data) {
console.log("here")
});
it seems like the event is never received, also I dont change anything on my server when I am changing from heroku to localhost
ps.
I have this in my server, I know I have to add this for heroku
global.io.configure(function () {
global.io.set("transports", ["xhr-polling"]);
global.io.set("polling duration", 10);
});
and my server side code when I emit the message looks like looks like:
exports.getFake = function(req, res){
global.io.of(global.id).emit('email' , email);
}
Web socket is experimental on Heroku.
Did you read this : https://devcenter.heroku.com/articles/heroku-labs-websockets ?
You may want to read this too : heroku multiple dyno socket.io

socket.io not working on several clients

I'm trying to build a simple chat client and am having some issues getting it working across multiple clients. Chances are I've missed something really simple. When I send something from one client it is logged in that client but not in any others.
Server:
var io = require('socket.io').listen(5000);
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
socket.emit('receive', data);
});
});
Client:
var socket = io.connect('http://localhost:5000');
socket.on('receive', function(data){
console.log("Data received at " + new Date() + ": " + data);
});
The socket variable that gets passed to your callback function is a handle on the client that connected, so socket.emit is behaving correctly, i.e. it should only send to the client that originated it.
Try:
socket.broadcast.emit('receive', data);
to send to everybody except the originating client, or
io.sockets.emit('receive', data);
to send to all clients including the originator.
You want to emit on all sockets, not just the one that sent the message.
So you should be using:
io.sockets.emit('recieve', data);
This is assuming that you aren't logging the data on the sending client before sending it to the server. In that case you'll want to use:
socket.broadcast.emit('recieve', data);
Which will send the message to all connected clients except the sender.
See here for reference on Socket.io
Edit: Trevor beat me to it. However, for some additional clarification: io.sockets is the same as io.of(''). Which is handy to know for when you start using namespaces in a scoket.io app.

Categories

Resources