node是如何实现websocket通信服务的?
在日常开发中,我们难免会遇到客服聊天这样的业务需求,那么双向通信到底是如何实现的,下面我以node安装websocket做具体介绍:
首先安装websocket:npm i ws -S
接着在js文件中:
// 导入websocket
const WebSocket = require("ws");
// 创建socket服务器并监听
const wss = new WebSocket.Server({ port: 3000 });
// 监听客户端连接, 并创建客户端socket
wss.on("connection", function connection(client) {
// 监听客户端发送的数据
client.on("message", function incoming(message) {
console.log("received: %s", message);
});
// 监听客户端连接关闭
client.on("close", function () {
console.log("close");
clearInterval(timer);
});
// 发送数据
const timer = setInterval(() => {
const res = {
code: 0,
msg: "ok",
action: "getServerTime",
data: [
{ id: 1, name: "Rose" },
{ id: 2, name: "Jack" },
],
};
client.send(JSON.stringify(res));
}, 1000);
});
console.log("socket服务器已启动...");
在客户端这样写:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>当前时间: <span></span></div>
<button>向服务器发送消息</button>
<script>
var client = new WebSocket("ws://127.0.0.1:3000");
client.onopen = function () {
console.log("连接成功");
};
client.onclose = function () {
console.log("断开连接");
};
client.onerror = function (ex) {
console.log("socket通信过程中的错误", ex);
};
client.onmessage = function (res) {
console.log(JSON.parse(res.data));
// document.querySelector("span").innerText = res.data;
};
document.querySelector("button").onclick = function () {
const req = {
action: "getServerTime",
params: {
id: 1,
name: "xxxx",
},
};
client.send(JSON.stringify(req));
};
</script>
</body>
</html>

浙公网安备 33010602011771号