首先WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。如果还不了解WebSocket的请移步 HTML5 WebSocket
在以前,我们处理点对点通信都只能使用轮询,原因是服务器不能主动向客户端发送信息。有了websocket,使得我们的点对点通信变得了更简单和更加高效。
废话不多说,这届上代码:
服务端app.js
// 使用koa
const koa = require('koa')
const router = require('koa-router')()
// koa-websocket是koa封装好的websocket功能
const websocket = require('koa-websocket')
// 实例化一个ws服务
const app = websocket(new koa())
// 用来存储建立了的链接,(真实项目中请使用数据库代替)
let wsObj = {}
// 监听koa/ws路由,是否有连接
router.all('/koa/ws', (ctx) => {
// 客户端链接传过来的客户端身份
const { id } = ctx.query
// 将链接保存起来
wsObj[id] = ctx;
// 给客户端发送链接成功信息
ctx.websocket.send('连接成功');
// 监听客户端发送过来的信息
ctx.websocket.on('message', function(message) {
console.log(message);
// uid为接收方,将接收到的信息发送给接收方uid,可以根据自己的需求处理数据再发送
const uid = JSON.parse(message).uId;
if(!wsObj[uid]){
ctx.websocket.send(`${uid}未上线`)
}else{
wsObj[uid].websocket.send(message)
}
});
})
// 使用路由
app.ws.use(router.routes()).use(router.allowedMethods())
//端口号后面可采用动态的
app.listen(3000, () =>
console.log('服务启动成功')
)
客户端调用index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>koa-websocket点对点通信</title>
</head>
<body>
<div id="loginDiv"
style="position: absolute;width:400px;height:200px;left:50%;top:50%;margin-left:-200px;margin-top:-100px;">
<div>
<label for="nameInput">连接的id(自己的id)</label>
<!-- 连接服务器 (上线)-->
<input type="text" id="nameInput" placeholder="请输入您的ID" />
<input type="button" value="连接" id="certainInput" onclick="ws()" />
</div>
<div>
<!-- 连接成功后,给某个id发动信息 -->
<label for="senid">给谁发送</label>
<input type="text" placeholder="发送到的id" id="sendId">
</div>
<div>
<label for="sendContent">发送的内容</label>
<input type="text" placeholder="发送的内容" id='sendContent'>
<input type="button" value="发送" onclick="send()">
</div>
</div>
</body>
<script type="text/javascript">
var webs = null; // websocket对象
var mId = null; // 我的id
function ws() {
mId = document.getElementById('nameInput').value;
webs = new WebSocket('ws://localhost:3000/koa/ws?id=' + mId)
webs.onopen = function () {
console.log('连接成功')
}
// 接收服务器发送的信息
webs.onmessage = function (evt) {
console.log(evt)
}
}
// 给特定的id发送信息,服务器接收后会向该id发送
function send() {
var id = document.getElementById('sendId').value;
var content = document.getElementById('sendContent').value;
var data = {
mId: mId,
uId: id,
content: content
}
webs.send(JSON.stringify(data))
}
</script>
</html>
效果
111用户
000用户