Nodejs using multiple files to catch events - javascript

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});
}

Related

How to send data between Node js and javascript in an html file

I am using an eye tracker and I want to create a website that displays this data in real time. I have the eye tracker notifying a Node js server and it provides data really consistently but when I used socket.io to send the data over it was buffering really slowly. I want a way to receive this data in a script in my index.html from the Node js server in real time or as close as possible. Any suggestions?
I have found my solution in socket.io-streams. Here's what I did:
in the app.js:
var ss = require('socket.io-stream');
var Readable = require('stream').Readable;
const io = require('socket.io')(http);
io.of('/data').on('connection', socket => {
var eyeTracker = ...
var listener = {
...
onGazeData:function(gazeData){ //trigger for recieving a gaze location
var s = new Readable()
s._read = function() {};
var stream = ss.createStream();
toSend = gazeData.x + "," + gazeData.y
s.push(toSend);
s.pipe(stream);
ss(socket).emit('gaze',stream);
}
}
eyeTracker.setListener(listener);
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
}
and in the index.js (linked to index.html) I put:
var ss = require('socket.io-stream');
$(function(){
var socket = io.connect('http://localhost:3000/data'); //or where ever you are running
socket.on('connect', function() {
ss(socket).on('gaze', function(stream) {
stream.on('data', function(data) {
//do what you want with data
})
})
});
//other parts of script outside of socket
});
This solution was able to keep up with the data being streamed.

Node.js Socket.io socket.brodcast is undefined

brodcast.emit to send a message to all without socket, and when I do that the node instance crashes and says that socket.brodcast is undefined .
here is my node code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
io.on('connection', function(socket){
socket.on("newChild",childData =>{
var newChildID = mainData.newChild(childData.fatherID,childData.data, childData.type);
socket.emit("newChildID",{ "newId" : newChildID,"old" : childData.localID});
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
});
});
when I emit "newChild" from the client the server crashes and say that socket.brodcast is undefined
The important part is to get socket.brodcast.emit , so do I use the API wrong?
when I googled after it I found this: Send response to all clients except sender (Socket.io)
In this thread I found this example:
socket.on('cursor', function(data) {
socket.broadcast.emit('msg', data);
});
And its seams to be the same as i do.
your code contains a typo for starters...
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
should be
socket.broadcast.emit("newChild",maindata.getDataPoint(newChildID));

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

socket.io reconnect socket.socket.connect doesn't work

sorry for posting this issue again, but most of the posts related don't answer my question.
i'm having issues to use multiple connections with the socket.io
i don't get the "socket.socket.connect" method to work, yet i get feedbacks from the first connection.
Here's my structure:
var iosocket = null;
var firstconnection = true;
var ip = "http://xxx.xxx.xxx"
var ipPort = 8081
function callSocket() {
iosocket = null;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
if (firstconnection) {
firstconnection= false;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
iosocket.on('connect', function () {console.log("hello socket");});
iosocket.on('message', function(message) {});//end of message io.socket
iosocket.on('disconnect', function () {console.log("disconnected");});
} else {
if (iosocket.connected === true) {
console.log("heyhey still connected");
iosocket.disconnect();
}
iosocket.socket.connect(ip,{port:ipPort,rememberTransport:true,timeout:1500});
}
};
it simply doesn't get any feedback from the second connection
i simply solved that IE8 bug by adding
<!DOCTYPE html>
at the top of the html
I think I know why this isn't working. For server-side code, this doesn't seem correct for socket.io. The connect method is used for clients and not servers. I think you are trying to make the server listen on a port. In that case, you should do:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
server.listen(8000);

socket.io parse connect (>= 2.4.1) signed session cookie

With the latest version of connect (as of 2012-07-26), I've found the following way to get a session ID from socket.io that will work with a connect-redis store.
var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');
var secret = '...';
var rStore = new(require('connect-redis')(express));
//...
var server = http.createServer(app);
var sio = io.listen(server);
sio.set('authorization', function(data, accept) {
if(data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
} else {
return accept('No cookie transmitted', false);
}
accept(null, true);
});
data.sessionID can then be used later such as
sio.sockets.on('connection', function(socket) {
console.log('New socket connection with ID: ' + socket.handshake.sessionID);
rStore.get(socket.handshake.sessionID, function(err, session) {
//...
});
});
Having to import so many from express (connect, a utility of connect, and the cookie module) seems like an overly roundabout way of getting the functions needed to parse connect's signed cookies. Has anyone found another way?
I was running into the same and just wrote a tiny module to abstract it. Here's how its usage looks like. It was written and tested using express 3 so should work fine with connect 2.4.x. Please let me know otherwise.
var SessionSockets = require('session.socket.io')
, sessionSockets = new SessionSockets(io, sessionStore, cookieParser);
sessionSockets.on('connection', function (err, socket, session) {
//your regular socket.io code goes here
});
For more details on how it works see https://github.com/wcamarao/session.socket.io

Categories

Resources