在日常开发中,我们难免会遇到客服聊天这样的业务需求,那么双向通信到底是如何实现的,下面我以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服务器已启动...");
在客户端这样写:
原文链接:https://www.cnblogs.com/baoxinyu/p/15293574.html