I am using koa and socket.io to serve both static html pages and process chat messages sent to the socket. The following code works as a server :-
var app = require('koa')();
var router = require('koa-router')();
var views = require('co-views');
var render = views('.', { map: { html: 'swig' }});
<--- [1]
router.get('/', function *(next) {
console.log('index.html');
this.body = yield render('index.html');
});
app.use(router.routes());
var server = require('http').createServer(app.callback()); <--- [2]
var io = require('socket.io')(server); <--- [3]
io.on('connection', function(socket) {
socket.on('chat message', function(msg, callback) {
console.log('got message - ' + msg);
io.emit('chat message', msg);
if (callback) {
callback();
}
});
});
server.listen(8080);
my question is; if I move [2] and [3] up to [1] with the rest of the server set up the get router doesn't work.
Does anyone know why?
The following is the client code :-
var io = require('socket.io-client');
var socket = io('http://localhost:8080');
socket.on('connect', function() {
console.log('socket connected');
socket.emit('chat message', 'hello world !!!!!!', function() {
console.log('emit');
socket.close();
});
});
socket.on('disconnect', function() {
console.log('socket disconnect');
});
When you call app.callback()
a callback function for handling HTTP requests is created. Based on the Koa source code it looks like the middleware stack is loaded into the callback when it is created. As such after the callback is created any further middleware added to the stack via the use()
method will not be used.
Following the same logic; if you were using the Koa listen()
method it would need to be called after all uses of the Koa use()
method. Otherwise these middlewares would not actually be on the middleware stack that the server is using.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments