当前位置: 首页 > 工具软件 > koa-socket-2 > 使用案例 >

node 基于Koa-socket-2 即时通讯

沃博裕
2023-12-01

资料:https://www.npmjs.com/package/koa-socket-2

           https://socket.io/docs/

           http://blog.fens.me/nodejs-socketio-chat/

          https://www.npmjs.com/package/socketio-jwt

安装模块

npm i -S koa-socket-2

 app.js -主程序

const Koa = require('koa');
const IO = require('koa-socket-2');
const app = new Koa();
const io = new IO();
const SocketRouter = require('./controls/SocketRouter ');
const socketioJwt = require('socketio-jwt');

// Attach the socket to the application
io.attach( app );

//json taken authorize
// app._io.use(socketioJwt.authorize({
//     secret: config.JWT_SECRET,
//     handshake: true
// }));

//soket middle
io.use( async ( ctx, next ) => {
    // ctx.socket = Socket;
    let start = new Date();
    await next();
    console.log( `response time: ${ new Date() - start }ms` );
});

//register all the listenning events
io.use(require('./router/socketRouter')(
    app.io,
    app._io,
    Object.assign({}, SocketRouters )
));
//connect the websocket
app.io.on( 'connection', async (ctx) => {
    infoLogger.info('websorket conncet success!');
    ctx.socket.emit('connects',{status:'conncet success!'});
});
//disconncect websocket
app.io.on('disconnect', async (ctx) => {
    infoLogger.info('websorke disconncect!');
});

module.exports = app;

www -启动文件

#!/usr/bin/env node
const app = require('../app');

const port = normalizePort(process.env.PORT || config.PORT);

// *If* you had manually attached an `app.server` yourself, you should do:
app.listen = function() {
    app.server.listen.apply(app.server, arguments);
    return app.server;
}
// app.listen is mapped to app.server.listen, so you can just do:
app.listen(port,() => {
    console.log(`http server listen on port:${port}!`)
});

/**
 * Normalize a port into a number, string, or false.
 */
function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

 socketRouter.js-路由

function noop() {}
/**
 * 路由处理
 * @param {IO} io koa socket io实例
 * @param {Object} routes 路由
 */
module.exports = function (io, _io, routes) {
    Object.keys(routes).forEach((route) => {
        io.on(route, noop); // register event
    });
    return async (ctx, next) => {
        if (routes[ctx.event]) {
            await routes[ctx.event](ctx);  //call event funciton
        }
        await next();
    };

};

SocketRouters -路由逻辑实现

module.exports =  {
    async data(ctx) {
        try {
            ctx.socket.emit( 'receive', {data:"a"});
        } catch (error) {
            console.log(error);
        }
    }
}

前端请求 socke.html

<script src="js/soket.io.js"></script>
var socket = io('http://192.168.1.111');

//connect success
socket.on('connects', function(datas) {
    socket.emit('data', {
		data: "test"
	});

    socket.on('receive', function(datas) {
        //
    }
}
//connnect fail

socket.on('disconnect',function(){
	
})

 

 

 类似资料: