Koa-mount/router + socket.io 整合

Koa-mount/router + socket.io integration

出于好奇,我选择了 Koa2 作为我的家庭 Node 服务器。不幸的是,我一直坚持为 client/server 通信实​​施 websockets。在以下应用程序中,socket.io 客户端拒绝连接到其服务器部分。有 idea/hints 吗?

// main.js
const argv = require('yargs');
const app = require('./src/app');
const conf = require('./config');

const port = argv.port || process.env.PORT || conf.port || 3000;

app.listen(port);

console.log(`IOKvit Server is listening on port ${ port }...`);

.......

// app.js
const Koa = require('koa');
const mount = require('koa-mount');
const router = require('./api');
const staticRoutes = require('./static');

const app = new Koa();

app.use(mount(staticRoutes));
app.use(router.routes());
app.use(router.allowedMethods());

const http = require('http');
const socket = require('socket.io');

const server = http.createServer(app.callback());
const io = new socket(server);

io.on('connection', function(socket){
    console.log('a user connected')
});

module.exports = app;

.......

// static.js
const Koa = require('koa');
const serve = require('koa-static');
const mount = require('koa-mount');
const path = require('path');

const staticApp = new Koa();
const root_dir = path.dirname(require.main.filename);

staticApp.use(serve(root_dir + '/static', { maxage: 60 * 1000 }));
staticApp.use(mount('/lib/vue', serve(root_dir + '/node_modules/vue/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/vue-material', serve(root_dir + '/node_modules/vue-material/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/vue-router', serve(root_dir + '/node_modules/vue-router/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/socket.io', serve(root_dir + '/node_modules/socket.io-client/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/roboto', serve(root_dir + '/node_modules/roboto-fontface/css/roboto/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/material-icons-font', serve(root_dir + '/node_modules/material-icons-font/', { maxage: 60 * 1000 })));

module.exports = staticApp;

.......

// api.js
const Router  = require('koa-router');
const house = require('./house').controller;

const router = new Router();

router.get('/rooms', house.list_rooms);
router.get('/rooms/:name', house.room);

module.exports = router;

我在 Koa (1.0.0) 中使用了这样的代码:

const koa = require("koa");
const socketIo = require("socket.io");

const app = koa();
const port = 8000
const http = app.listen(port); 
const io = socketIo.listen(http); 

io.on("connection", function(socket){ 
  console.log("connected")
})