在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:LnsooXD/koa-socket.io开源软件地址:https://github.com/LnsooXD/koa-socket.io开源编程语言:JavaScript 90.8%开源软件介绍:koa-socket.io
Middleware for Koa2 to get/set session use with custom stores such as Redis or mongodb Use native ES6(async/await) by Nodejs v7.6, use Or you can use the old versions: koa-socket.io now requires node v7.6.0 or higher although koa-socket.io simply attaches to the server instance so will be compatible with a koa v1 powered app. If you need use koa-socket.io on lower version that requires node v4.0.0 or higher, plase use koa-socket.io v1.0.3 Installationnpm i -S koa-socket.io Example
git clone https://github.com/LnsooXD/koa-socket.io.git koa-socket.io
cd koa-socket.io
export NODE_ENV=development
npm install
npm run example
const Koa = require( 'koa' )
const IO = require( 'koa-socket.io' )
const http = require('http');
const app = new Koa()
const io = new IO({
namespace: '/'
})
app.use( ... )
let options = {
/* socket.io options */
}
var server = http.createServer(app.callback());
io.start( server, options/*, port, host */ )
io.on('join', function* () {
console.log('join event receiverd, new user: ', this.data)
// use global io send borad cast
io.emit('msg', '[All]: ' + this.data + ' joind');
// use current socket send a broadcast
this.socket.broadcast('msg', '[All]: Hello guys, I\'m ' + this.data + '.');
// just send to current user
this.socket.emit('msg', '[' + this.data + ']' + " Welcome to koa-socket.io !");
})
server.listen( process.env.PORT || 3000 ) Features
Middleware and event handlersMiddleware can be added in much the same way as it can be added to any regular koa instance. io.use(function* (next){
let start = new Date()
yield next;
console.log( `response time: ${ new Date() - start }ms` )
}) Passed Context
io.use( function* (next ) {
this.process = process.pid
yield next;
})
io.use( function *(next ) => {
// ctx is passed along so ctx.process is now available
console.log( this.process )
})
io.on( 'event', function*(next) => {
// ctx is passed all the way through to the end point
console.log( this.process )
}) NamespacesNamespaces can be defined simply by instantiating a new instance of const app = new Koa()
const chat = new IO({
namespace: 'chat'
})
chat.start( app.server )
chat.on( 'message', function*(next) {
console.log( this.data )
chat.broadcast( 'response', ... )
}) Namespaces also attach themselves to the const app = new Koa()
const chat = new IO({
namespace: 'chat'
})
chat.start( app.server )
chat.use( ... )
chat.on( ... )
chat.broadcast( ... ) API
.start( |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论