注意,前情提示:
本代码基于《Node.js(nodejs)对本地JSON文件进行增、删、改、查操作(轻车熟路)》
首先安装
cnpm i nodejs-websocket
在/api/demo/文件夹下面创建websocket.js
代码内容
const $g = global.SG.$g, fs = global.SG.fs, router = global.SG.router, ws = global.SG.websocket;
module.exports = global.SG.router;
//创建websocket----------------------------------------------------------------
console.log("开始建立连接...");
const port = 10000;//设置websocket占用的端口号,强哥酷爱一万号!
let server = ws.createServer(socket => {
socket.on("text", str => {
console.log($g.date.nowtime() + "收到客户端的信息:" + str);
//socket.sendText("收到客户端的信息:" + str);//只推送给当前连接的一个终端
server.connections.forEach(conn => conn.sendText("收到客户端的信息:" + str));//全局广播
});
socket.on("close", (code, reason) => {
console.log($g.date.nowtime() + "关闭连接");
});
socket.on("error", (code, reason) => {
console.log($g.date.nowtime() + "异常关闭");
});
}).listen(port);
console.log(`WebSocket建立完毕,地址为:ws://localhost:${port}`);
在index.js最后一行加入
app.use(API_PATH, require(`.${API_PATH}/demo/websocket`));//websocket
运行
node index
接下来打开创建客户端访问的模拟页面,随便新建一个index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<button>正在连接…</button>
<div class="msg"></div>
</body>
<script>
var button = document.querySelector("button");
var msg = document.querySelector(".msg");
if (window.WebSocket) {
var ws = new WebSocket("ws://localhost:10000");
ws.onopen = function (e) {
button.innerHTML = "连接服务器成功";
};
ws.onclose = function (e) {
button.innerHTML = "服务器关闭";
};
ws.onerror = function () {
button.innerHTML = "连接出错";
};
ws.onmessage = function (e) {
console.log(e.data);
button.innerHTML = "连接成功,点击发送信息给服务器";
msg.innerHTML += `<p><b>[服务器发来信息]</b>${e.data}</p>`;
};
document.querySelector("button").onclick = function (e) {
ws.send(new Date().toLocaleString("zh-Hans-CN", {hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false}));
};
}
</script>
</html>
运行该index.html
多次点击按钮你会看到网页里面出现了
同时去看下服务端的控制台
会了吗?理解了WebSocket的原理了吗,欢迎给我留言哟~
标签:node,websocket,log,button,console,js,ws,WebSocket From: https://blog.51cto.com/u_15920212/5962879