技术栈
服务端:
koa、koa-route、koa-websocket、request。
客户端:
html、css、js、websocket。
远程聊天API:
http://api.qingyunke.com/api.php?key=free&appid=0&msg=msg。
客户端展示
开发步骤
1.在桌面创建bbs文件夹,然后在文件夹内打开cmd,输入:
$ npm init
初始化箱项目,生成package.json包管理文件
2.cmd输入:
$ npm install koa --save
安装koa。
3.cmd输入:
$ npm install koa-route --save
安装koa路由模块。
4.cmd输入:
$ npm install koa-websocket --save
安装koawebsocket模块。
我的package.json:
{ "name": "bbs", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" }, "author": "", "license": "ISC", "dependencies": { "koa": "^2.8.1", "koa-route": "^3.2.0", "koa-websocket": "^6.0.0" } }
5.在bbs文件夹中新建server.js,项目启动入口文件。
添加内容如下:
const Koa = require('koa'), route = require('koa-route'), websockify = require('koa-websocket'), http = require('http'), app = websockify(new Koa()); app.ws.use(route.all('/', ctx => { // websocket作为“ctx.websocket”添加到上下文中。 ctx.websocket.on('message', message => { startRequest(message, ctx); }); })); function startRequest(message, ctx) { // 采用http模块向服务器发起一次get请求 http.get(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${encodeURI(message)}`, res => { // 防止中文乱码 res.setEncoding('utf-8'); // 监听data事件,每次取一块数据 res.on('data', chunk => { ctx.websocket.send(JSON.parse(chunk).content); }); }).on('error', err => { ctx.websocket.send('对不起,网络故障了'); });} // 监听端口、启动程序 app.listen(3000, err => { if (err) throw err; console.log('websocket服务器启动在3000端口'); })
假如对server.js还不清楚的,可以留言或者邮件咨询我。
6.在bbs文件夹中新建index.html文件,作为客户端展示文件。
添加内容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>实时聊天室</title> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <div class="box"> <div class="title">实时聊天室</div> <div class="input-box"> <input class="input" placeholder="你想说什么..." type="text" id="pl" onkeydown="keyEnter()" /> <div class="send" id="submit">发送</div> </div> <div class="view" id="ulView"> <ul id="view"></ul> </div> </div> <script src="index.js"></script> </body> </html>
7.在bbs文件夹中新建index.css,客户端的样式。
内容如下:
* { padding: 0; margin: 0; -webkit-user-select: none; -moz-user-select: none; } html, body { height: 100%; width: 100%; background-color: #333; position: relative; font-size: 12px; } .box { position: absolute; top: 50%; left: 50%; transform: transl