3

I am used to the way routing works in node.js however let me give you a typical example of a socket.io node server:

 /** * Created by root on 3/13/15. */ var multer = require('multer'); var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var cookieParser = require('socket.io-cookie-parser'); var moment = require('moment'); var mysql = require('mysql'); var users = []; var message = ""; io.use(cookieParser()); io.on('connection', function (socket) { var userDetails = {}; /* Connection (after login) */ socket.on('userData', function (userDetails) { users[userDetails.id] = socket; userDetails = userDetails; }); //Notification socket.on('sendNotification', function (users, notification) { users.forEach(function (y) { if(users[y] != null){ users[y].emit(notification); } }) }); socket.emit('newNotification', 'hell'); socket.emit('someEvent', 'hello world'); socket.on('browserClose', function (msg) { console.log('this user has disconnect: ' + userDetails.username); users[userDetails.id] = null; }); //check connection / status of other sockets: socket.on('isOnline', function(user_id){ socket.emit('userStatus', users[user_id] != null); }); socket.on('setMyLocation', function(location){ users[userDetails.id].location = location; }); }); http.listen(8105, function () { console.log('listening on *:8105'); }); 

This works fine. however when the need to expand and create multiple functions such as chat and streaming this file can be come very long and hard to maintain.

So my question is how do you split socket connection into different files and is it even possible?

What im looking for here is some best pratice usage gladly with some examples.

1 Answer 1

5

Try out following code:

socketio.on('connection', function (socket) { // ... socket.on('isOnline', function (user_id) { require('user-online.js').register(socket, user_id); }); socket.on('sendNotification', function (args) { require('notification/handler.js').handler(socket, args); }); // ... }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.