express + socket.ioのミニマム構成
express + socket.ioのサンプルを漁っていると、nodeの createServer を使ってhttp.Serverを作成しsocke.ioで使い回す実装をよく見かける。express 4系からは、nodeのhttpモジュールを使わずにlistenできるようになっているので、これを使ってシンプルに実装することができる。
ポイントはapp.listen()の戻り値がhttp.Serverであること。appを直接 socketIO() の引数に取ると次のようなエラーが発生する
Error: You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
code:typescript
import * as express from 'express';
import * as socketIO from 'socket.io';
export const main = () => {
const app = express();
// node http.Server is returned.
const server = app.listen(3000, () => console.log(listening on port 3000));
const io = socketIO(server);
/**
* configure socket.io events handling.
*/
io.on('connection', (socket) => {
// socket.on(...)
});
};
main();
参考
http モジュールは、このモジュールを直接処理する必要がある場合を除き、不要になりました (socket.io/SPDY/HTTPS)。アプリケーションは、app.listen() 関数を使用して開始できます。
httpモジュールを使った実装