Socket IO - NodeJS require external script? - javascript

I have a question regarding requiring scripts to the NodeJS / Socket.IO Server.
In PHP I can add the line require('somefile.php');
Is there any option to include any JS files to the NodeJS/Socket.IO server? My server code currently has over 500 lines, I want to add a Require for each Socket.On to make it easier to read.
Is there a disadvantage?
Thanks,
David :))

You can in this way,
Your IO Connection file,
var module1 = require('file1.js');
var module2 = require('file2.js');
io.on('connection', function (socket) {
module1(socket);
module2(socket);
})
file1.js,
module.exports = function (socket) {
socket.on('createroom', function (data) {
console.log("create room");
});
}
file2.js,
module.exports = function (socket) {
socket.on('play', function (data) {
console.log("play");
});
}

Related

Socket.io inside Node.js backend routes

Okay. so im trying to achieve to get socket.io inside all my express routes.
a portion of my code:
var port = process.env.PORT || 3000; // set our port
var server = app.listen(port);
var io = require('socket.io')(server);
app.io = io;
exports.io = io;
then i call it as follows inside other file.
var app = require('../../server');
var io = app.io;
function hijack(user,boatid) {
console.log("????");
console.log(user);
app.io.sockets.emit("myevent",{ test: 22});
var userid = user._id;
console.log(user);
}
module.exports = {
hijack : hijack(app),
};
But, it seems like user parameter inside hijack function now is occupied by the app, and, iff i add an exstra parameter, it still dont know the user parameter, as im calling in the main file by the following:
var ships_model = require('./app/gamemodels/ship_model.js');
ships_model.hijack(req.user, req.body.id).then(function (result) {
res.json(result);
});
Please note: i tried to inject the IO like the following:
var ships_model = require('./app/gamemodels/ship_model.js')(io);
but that just produced errors.
another example:
Is it possible to make a socket emit call within some functions? im only intrested to emit data to the client side.
Or how pusher server sided is working, could that be done with socket too?
the client request is as follows server sided
var bankfactory = require(path.resolve('./modules/articles/server/factory/user_factory.js'));
app.post('/api/bank', function (req, res) {
bankfactory.bank_inn(req.user._id,amount).then( function (bankresult) {
res.json(bankresult);
});
});
bankfactory:
exports.bank_inn = bank_inn;
function bank_inn(playerid,amount) {
if (playerid == 1) {
} else {
// possible to make a emit call to the client here?
//emit("newevent,datahere)
}
}
Note two: I already looked into eventemiters, but with no results.
So, how can i achieve to call socket.emit inside my express routes?
Additional structure code:
main file:
var ships_model = require('./app/gamemodels/ship_model.js');
ships_model.createShipInterface(req.user._id).then(function (response) {
res.json(response);
});
ship_model file have the following structure:
module.exports = {
getShips: getShips(),
createShipInterface : createShipInterface,
allowedLocationsShips : allowedLocationsShips,
startMissionInterface : startMissionInterface,
deligateShipMovements: deligateShipMovements,
upgradeBoat : upgradeBoat,
deletedBoats: deletedBoats,
hijackSession : hijackSession,
boats_to_hijack : boats_to_hijack,
avaliable_boats : avaliable_boats,
createHijackSession : createHijackSession,
public_hijack : public_hijack,
joinHijackSession : joinHijackSession,
leavehijack : leavehijack,
sendMessageToMembers : sendMessageToMembers,
KickMember : KickMember,
togglePublic : togglePublic,
getHangar : getHangar,
hijack : hijack(app),
getHangarSession: getHangarSession,
updateUserLocation : updateUserLocation,
};
As per your comment
So, how can i achieve to call socket.emit inside my express routes?
In our project, what we have done is create a socket server and express server. Thus both express server(server-socket) and browser(client-socket) are clients of socket server.
So whenever express server want to send something to browser, it send data to socket server with the identifier of browser(socket-Id or other unique identifier of client socket) to which we want to send. Then socket server using the identifier send data to the particular browser.

Nodejs using multiple files to catch events

I was wondering if it was possible to use multiple files on nodeJS that will catch events and handle them?
For example right now I have a server.js which is filled with code to handle chats and chatrooms.
Which would briefly just look as follow
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
server.listen(1234);
io.on('connection', function(client){
client.on('room_join', function(roomId){(
client.join(roomId);
});
client.on('message', function(data){
io.to(data.roomId).emit('message', {message: data.message});
});
});
Now what I would prefer if possible, is to create a messages.js, and rooms.js file that will handle this. But I would actually prefer those catching the events aswell. So my rooms.js file would look something like this
//rooms.js
client.on('room_join', function(roomId){( //Catching the event
client.join(roomId); //Still able to handle the client property made in the sever.js
});
Is such thing possible, or can I only require the rooms.js file and use it as follow
var rooms = require('modules/rooms.js');
client.on('room_join', function(roomId){
rooms.join(roomId);
});
A prefered solution would be something with the following structure
//server.js
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
var messagesEvents = require('events/messages.js');
var roomEvents = require('events/rooms.js');
server.listen(1234);
// events/messages.js
var messages = require('../modules/messages.js');
io.on('connection', function(client){
client.on('message', function(data){
messages.send(client, data, io);
});
});
// modules/messages.js
function send(client, data, io){
return io.to(data.roomId).emit('message', {message: data.message});
}

socket.io connection not heppening

This is first time, I am using socket.io.I stuck at initial stage itself.sorry it's may be simple question.
server side code :
Inside my server.js I written the following code.
var express = require('express')
,io=require('socket.io')
,http = require('http')
var app = express();
server = http.createServer(app);
io = io.listen(server,{ log: false });
Now I trying to make connection inside server.js file,like in the following way.
io.sockets.on('connection', function (socket) {
console.log("This is testing");
io.to(socket.id).emit('notification', 'for your eyes only');
});
client side code :
var socket = io.connect("http://localhost");
socket.on('connect', function () {
console.log("connect")
});
socket.on('notification', function (data) {
console.log(data);
});
I open application in browser, as per my code it suppose to console connect statement but it's not happening.
my server is running on port no :80Where am I did wrong, can anyone help me.
Thanks.
Here is the working code for me in express it may help you.
var express = require('express')
, app = express()
, server = require('http').Server(app)
, io = require('socket.io')(server)
var defaultPort = 6001 ;
server.listen(defaultPort, function() {
console.log('Server Started');
});
io.sockets.once('connection', function(socket) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: "Your Data Goes Here"
});
socket.on('disconnect', function(){
});
});
On Client Side
<script>
$(function() {
var socket = io.connect('http://localhost'); //if you are trying on server put server url if you are working on local then use localhost
socket.on('new-data', function(data) {
$('#YouDivid').html(data.value);
});
});
</script>

Javascript Globals and Socket.io

Is there any "globals" function in Javascript which is similar to PHP globals that would apply in this example?
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
querystring = require('querystring');
app.listen(8000);
var content = '';
function handler(req, res) {
io.sockets.on('connection', function (socket) {
if(req.method == 'POST') {
var fullBody = '';
req.on('data', function(chunk) {
fullBody += chunk.toString();
});
req.on('end', function() {
var decodedBody = querystring.parse(fullBody);
console.log(decodedBody);
socket.emit('user-aaa5c8bbffe4db9', fullBody);
});
}
});
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);
});
}
I wrote a PHP app but I want to have notifications through socket.io but I don't want to rewrite the app for Node.js (yet) so I setup a Node server which the PHP will send a POST to and then the server will send the notification via Socket.io. I've tested the server with basic scripts and they do work. I've also tried moving the "io.sockets.on('connection', function (socket) {" inside the IF statement:
req.on('end', function() {
var decodedBody = querystring.parse(fullBody);
console.log(decodedBody);
io.sockets.on('connection', function (socket) {
socket.emit('user-aaa5c8bbffe4db9', fullBody);
});
});
But that did not produce "instant" results, the notifications would come in to the client after a page refresh.
Client is a simple:
socket.on('user-<?php echo $_SESSION['user_display_id']; ?>', function (data) {
alert(data);
$('#events').html(data);
});
Any help would be greatly appreciated
To answer your first question. No there is no global in JavaScript. All the variables that are in scope where the function is defined will be available in that function.
http://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/
In node.js there's the object global.
You can assign to its property some values and they will be accesible everywhere, but I think it is not best practice.

socket.io: client-side emit callback never fires

Messing around with socket.io just for proof of concept, everthing is working great so far except I can't get my emit callback to work on the client side. I've got to be missing something stupid here, but documentation is not killer at the moment. The server picks up the "getSomeData" event just fine, no errors anywhere.
From what I could tell in the client socket.io source, it checks if the last argument to emit is a function and always uses it as a callback, but debugging any deeper than that was problematic for me.
I feel like I have to be missing some core concept here..Is this not what this.send(..) is supposed to do? I could find only 1 useage in the example apps, and none where the client side code for that event emission was available.
Update: just to be clear, I am in fact intentionally emitting the event client side. The purpose of this was to see if socket.io could be used to allow clients to pull data on request in addition to receiving pushes.
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on("getSomeData", function() {
this.send({data: "some random data"});
});
});
client: (console.log never happens)
<script type="text/javascript" src="http://localhost/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost');
socket.emit("getSomeData", function(data) {
console.log(data);
});
</script>
It looks like you have some logic switched around, try...
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit("getSomeData",{data: "some random data"});
});
and client...
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on("getSomeData", function(data) {
console.log(data);
});
</script>
EDIT:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.on("getSomeData", function(name,fn) {
fn({data: "some random data"});
});
});
Client
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.emit("getSomeData", function(data) {
console.log(data);
});
</script>
In Liam William's answer, I found it was necessary to send the callback (or acknowledgement function) as the third argument on the client emit:
Client:
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.emit("getSomeData", null, function(data) {
console.log(data);
});
You can have the callback, but you have to do it a bit differently:
Server: (app.js)
var io = require('socket.io')(80);
io.on('connection', function (socket) {
// please note that server will take 2 data entries as function parameter below
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
Client (index.html)
var socket = io(); // TIP: io() with no args does auto-discovery
socket.on('connect', function () {
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
Actaully, socket io also mentions this one; sending-and-getting-data-(acknowledgements)

Categories

Resources