我习惯了node.js中的路由工作方式,但是让我给你一个socket.io节点服务器的典型例子:
/**
* 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');
});
这很好用。但是当需要扩展和创建聊天和流媒体等多种功能时,这个文件可能会很长很难维护。
所以我的问题是如何将套接字连接分成不同的文件,甚至可能?
我在这里寻找的是一些最好的实践用法,很高兴地举例说明。
答案 0 :(得分:3)
尝试以下代码:
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);
});
// ...
});