编程语言
首页 > 编程语言> > javascript-套接字io将函数拆分为不同的文件

javascript-套接字io将函数拆分为不同的文件

作者:互联网

我已经习惯了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');
});

这很好.但是,当需要扩展和创建诸如聊天和流媒体之类的多种功能时,此文件可能会变得很长且难以维护.

所以我的问题是如何将套接字连接拆分为不同的文件,甚至有可能吗?

我在这里寻找的是一些示例的最佳实践.

解决方法:

试用以下代码:

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

  // ...  
});

标签:node-js,sockets,socket-io,javascript
来源: https://codeday.me/bug/20191120/2043226.html