Node.js Socket.io seperate connection events for each page - javascript

I've taken the following code from Socket.io documentations page.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I would like to have a separate 'connection' event depending on the page that made the request. E.g.
Clients connected from the 'index' page trigger this event.
io.on('connection', function (socket) {
console.log('connected from the index page');
});
and
clients connected from the 'player scores' page trigger this event
io.on('connection', function (socket) {
console.log('connected from the index page');
});
I've considered using namespaces. Is there a way that I could do this without out the client having to specify that it has connected from a particular page?
Regards,

You could use the handshake data in the socket object to get the URL and then program the different pieces of logic in an if-statement. Something along these lines:
io.on('connection', function (socket) {
if(socket.handshake.url == "index url you expect"){
console.log('connected from the index page');
} else if(socket.handshake.url == "player scores url you expect"){
console.log('connected from the player scores page');
}
});

Related

Socket.io Basic web socket connection with url?

My client is making a WebSocket request to this URL: ws://localhost:3000/feed/XBTMUR
In my server, I have NodeJs running express. I want to use Socket.io to listen to clients connecting to this URL and send feed data regularly.
I tried this but it is not working:
var app = require('../app');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
var io = require('socket.io')(server);
var feed =
io.of('/feed/XBTMUR').on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
setInterval(()=>{
io.sockets.emit('this', { receivers: 'everyone'});
},1000)
server.listen(port);
The client is not using Socket io.
I feel the the implementation is wrong while reading the documentation.
var feed = io.of('/feed') // `/feed` is the namespace
.on('connection', function (socket) {
socket.to('XBTMUR', { hello: 'world' }); // `XBTMUR` is the room / socket id
});
Hope this helps.

how to request the url in socket.io

I am trying get the json data from url example.com and pass that to my index.html. How can I do that. It's not working. I want to update data every 5 second file index.html.
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var https = require('https');
app.get('/', function(req, res) {
res.sendfile('index.html');
//How to use req object ?
});
io.on('connection', function(socket) {
console.log('A user connected');
setInterval(function() {
urlString = "https://example.com/trip?trip_id=1234";
$.get(urlString, function(data, status){
console.log('data');
})
socket.send('');
}, 4000);
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){document.write(data)});
</script>
You were doing a number of things wrong:
$.get() doesn't run on the server. That's client-side jQuery code
You should create one setInterval() on your server, not a new one for each client connection
You can then just broadcast the results to all connected clients
If you document.write() in the client after the page is loaded, it just clears your original document so you want to append info to the DOM, not use document.write().
When you send data with socket.io, you send a message name and some data .emit(someMessage, someData).
Here's one way to do your code:
// server.js
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const request = require('request');
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// create one and only one interval
setInterval(function() {
let urlString = "https://example.com/trip?trip_id=1234";
request(urlString, function(err, response, data) {
if (err) {
console.log("error on request", err);
} else {
console.log('data');
// send to all connected clients
io.emit('message', data);
}
});
}, 5000);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
server.listen(3000, function() {
console.log('listening on *:3000');
});
// index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){
let div = document.createElement("div");
div.innerHTML = data;
document.body.appendChild(div);
});
</script>

Socket.io not Emitting from Client nor Server?

On client side, I have this code:
var serverAddress = "http://localhost:8081";
var socket = io(serverAddress);
socket.on('connect', function(){
console.log("Connected to server on %s", serverAddress);
});
socket.emit("xxx", {text : "attack"});
And on server, I have this one:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
socket.on('connect', function() {
console.log('A user is connected to server');
});
socket.on('xxx', function(data) {
console.log(data);
});
connect event is fired and caught on server, but xxx event isn't even fired nor caught. What's wrong? Console.log didn't report any error.
You're confusing the socket.io server with a socket.io connection.
The server receives a connection event when a new client connection is made. The argument for that event (usually called socket) represents that connection. This is the object that you need to use to listen to messages:
// server
...
var io = require('socket.io').listen(server);
...
io.on('connection', function(socket) {
console.log('A user is connected to server');
socket.on('xxx', function(data) {
console.log(data);
});
});

Node.js and Socket.io moving from local development server to live server, not connecting

I have built a private chat system using Node.js and Socket.io on my local development server, and it is working fine, sends messages, updates the database whenever the client accepts the message event. However, the past two days I have been trying to push this to my live Rackspace server. I have been chatting with Rackspace and they have spun up my node server, I have a console.log that prints "Server listening on port: xxxx". I will post my node.js server code as well as some of my client code. I am just not sure what is going wrong as it worked fine on my local development. Chrome console is giving me a error of 'io is not defined' which it is, which is making me think that it is not loading the socket.io/socket.io.js from the node server. However, I thought that it would give me an error on the GET request.
I am new to Node.js and Socket.io and do not understand everything about it. I am trying to use this on vhost host, could this cause a problem?
var express = require('express');
app = require('http').createServer(handler),
//server = require('http').createServer(app),
io = require('socket.io')(app);
fs = require('fs');
app.listen(3000, function() {
console.log("Server listening on: 3000");
});
var clients = {};
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
//app.get('/', function(req, res){
// res.sendFile(__dirname + '/index.html');
//});
io.sockets.on('connection', function(socket){
console.log("Connected!");
socket.emit('news', { hello: 'world' });
socket.on('add-user', function(data){
clients[data.username] = {"socket" : socket.id};
console.log(data.username+' / '+clients[data.username].socket);
});
socket.on('private-message', function(data){
console.log("Sending: " + data.content + " to " + data.username);
if (clients[data.username]){
io.sockets.connected[clients[data.username].socket].emit("add- message", data);
} else {
console.log("User does not exist: " + data.username);
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
for(var name in clients) {
if(clients[name].socket === socket.id) {
delete clients[name];
break;
}
}
});
});
Client Code:
var socket = io;
socket.connect('x.x.x.x:3000');
var viewingUser = $('#viewingUserID').val();
socket.on("news", function (data) {
console.log(data);
});
socket.emit("add-user", {"username" : viewingUser });
So I replaced "<script type="text/javascript" src="xx.xxx.xxx.xxx:3000/socket.io/socket.io.js">" with "<script type="text/javascript" src="https://cdn.socket.io/socket.io-1.3.5.js"></script>"
This is the error:
GET http://23.253.247.166:3000/socket.io/?EIO=3&transport=polling&t=1439565622045-29 net::ERR_CONNECTION_REFUSED
Your server does not have a request handler for the socket.io javascript file.
You browse to your website and your server gets a request, you handle it by sending the index.html file.
When the index.html file is being processed by the browser, it will find the socket.io script tag and make a request to the server for it, but you only respond to requests by sending the index.html file.
Either:
Try replacing the script tag src with a CDN version of socket.io (client version).
or
Add a request handler to send the javascript file when requested
If you have to serve static content (like webpages / javascript / css / images / ...) express makes it very easy:
app.use(express.static('public')); Where public would be the folder of your static assets.
Server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
// Socket stuff goes here. but try this for a start
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('Server listening on:3000');
});

Why can't I see in console.log() the server code of socket.io?

I am starting to learn how to use socket.io and I've been trying to figure this out for the last couple of days but I don't get 2 things.
Why, after starting the server and loading my respective url (localhost:8088) does it take so long for my alert to show up?
Why can't I see the server code of socket.io? for example in the next chunk of code I never see in console my data from "my other event".
server (app.js):
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(8088);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
console.log(data);
});
});
client (index.html):
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
alert(data.hello);
socket.emit('my other event', {
my: 'data'
});
});
</script>
It might be the incompability between express 3.0 and socket.io
Try this:
var express = require('express'),;
var http = require('http');
var app = express();
var server = module.exports = http.createServer(app);
var io = require("socket.io").listen(server);
server.listen(8088);

Categories

Resources