koa实现socket.io 详解怎样使用koa实现socket.io官网的例子
kaseisai 人气:2socket.io官网中使用express实现了一个最简单的IM即时聊天,今天我们使用koa来实现一下
### 框架准备
1.确保你本地已经安装好了nodejs和npm,使用koa要求node版本>7.6
2.在你需要的位置新建一个文件夹(官网的简单命名为chat-example)
3.进入项目目录,创建package.json文件:
{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {} }
4.命令行中使用npm安装,执行以下命令
npm install --save koa koa-router http fs socket.io
### 接下来直接上代码
项目目录下直接新建index.js
var Koa = require('koa'); var app = new Koa(); const Router = require('koa-router'); const fs = require('fs'); const server = require('http').createServer(app.callback()); const io = require('socket.io')(server); // 首页路由 let router = new Router(); router.get('/', ctx => { ctx.response.type = 'html'; ctx.response.body = fs.createReadStream('./index.html'); }); app.use(router.routes()); // socket连接 io.on('connection', (socket) => { socket.on('chat message', (msg) => { console.log('message: '+msg); io.emit('chat message', msg); }); socket.on('disconnect', () => { console.log('user disconnected'); }); }); // 监听端口 server.listen(3000, () => { console.log('listening on *:3000'); });
重点:
socket的连接方式是先建立server,它的获取方式不再是:
var http = require('http').Server(app); var io = require('socket.io')(http);
而变成了:
const server = require('http').createServer(app.callback()); const io = require('socket.io')(server);
node8之后,function(){} 可以简化为 () => {},写法上更加的简洁
页面index.html
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function () { var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#message').append($('<li>').text(msg)); }); }); </script> </body> </html>
index.html和官网的一样,不做任何改动
最后执行node index.js,打开浏览器,输入http://localhost:3000就可以实现最简单的聊天了
加载全部内容