简述如何使用node+express实现接口链接及入门websocket通信。使用技术栈:node + express + typescript + websocket。前端
这里描述前端如何模拟实现接口请求,使用的是express(基于node实现的能够快速搭建web应用的开发框架),这里使用node+express搭建一个简单的web服务器。node
1) 初始化生成一个新的 package.json
文件web
npm init -y //-y(表明yes),跳过提问阶段,直接生成文件。
2)安装须要使用的npm包:node
, express
,ws
(即websocket)typescript
npm install node express ws --save
3)这里使用ts开发,因此须要安装ts须要使用的类型定义包(若是使用js就不要安装了)express
npm install @types/node @types/express @types/ws -- save
4)安装node热更新依赖包nodemon
npm
npm install nodemon --save
新建demo-server.ts
文件
1)数据模拟json
// demo-server.ts export class Demodata { constructor( public id: number, public name: string, public desc: string) { } } const datas: Array<Demodata> = [ new Demodata(1, 'heimayu', 'this is my bolg name'), new Demodata(2, 'websocket', 'this chapter is introduce websocket'), new Demodata(3, 'express', 'you can use express to start webapp') ]
2)使用express快速搭建web服务器服务器
// demo-server.ts import * as express from 'express'; const app = express(); // 启动服务器 app.listen(8001,'localhost',_=>{ console.log('demo服务器已启动,访问地址http://localhost:8001') })
// 接口请求-获取数据 app.get('/datas', (req, res) => { res.send(datas) //数据发送 }) // 接口请求-根据id获取数据 app.get('/datas/:id', (req, res) => { let url_id: number = req.params.id; let data: Demodata = datas.find(item => { return item.id == url_id }); res.send(data); })
将ts文件转换成js文件后启动热更新命令 nodemon build/demo-server.js
websocket
访问 http://localhost:8001/datas
app
访问 http://localhost:8001/datas/1
接口实现!
WebSocket 是 HTML5 开始提供的一种在单个 TCP 链接上进行全双工通信的协议。
【举例】:好比咱们须要定时的获取即时消息数,若是使用http请求,就必须轮询,不停的建立http请求,资源浪费严重,此时可使用websocket来解决问题,使通讯更加高效。
node实现websocket有不少模块可实现,这里使用的是ws模块
npm install ws --save
import { Server } from 'ws'; // 定义websocket服务器 const wsServer = new Server({ port: 8085 }); // 定义链接到的websocket集合 let socketSet = new Set<any>(); // 链接 wsServer.on('connection', websocket => { socketSet.add(websocket) }); // 初始化消息数 let message = 0; // 定时2s发送消息 setInterval(() => { socketSet.forEach(ws => { if (ws.readyState == 1) { ws.send(JSON.stringify({ message: message++ })) } else { socketSet.delete(ws); } }) }, 2000)
/** * url:链接的url * protocol:可选,接受的子协议 **/ var ws = new WebSocket(url,[protocol])
ws.readyState
事件 | 描述 |
---|---|
open | 链接创建时触发 |
message | 客户端接收服务端数据时触发 |
error | 通讯发生错误 |
close | 链接关闭时触发 |
方法 | 描述 |
---|---|
send() | 使用链接发送数据 |
close() | 关闭链接 |
// angular代码 message: number = 0; // 消息数 ws: WebSocket; // 定义 ngOnInit() { // 初始化 this.ws = new WebSocket('ws://localhost:8085'); // 客户端接收消息 this.ws.onmessage = (event) =>{ this.message = JSON.parse(event.data).message; } // 出错 this.ws.onerror = (error) =>{ console.log(error); } // 关闭 this.ws.onclose = ()=>{ console.log('webSocket断开链接') } }
即时通信成功!