{
"scripts": {
"dev": "node ws.js",
"ncc": "ncc build ./ws.js -m -o ./dist/"
},
"dependencies": {
"@vercel/ncc": "^0.36.1",
"ws": "^8.13.0"
}
}
const http = require("http");
const fs = require("fs");
const { WebSocket, WebSocketServer } = require("ws");
var fun = function (request, response) {
var stream = fs.createReadStream("./ws.html", {
flag: "r",
encoding: "utf8",
});
stream.pipe(response);
};
var server = http.createServer(fun).listen(9091);
var wsServer = new WebSocketServer({ server: server });
wsServer.broadcast = (msg) => {
wsServer.clients.forEach((client) => {
if (client.readyState == WebSocket.OPEN) {
client.send("【广播】" + msg);
console.log(666.789, wsServer.clients);
}
});
};
wsServer.on("connection", (ws, req) => {
console.log(666.1001, ws, req);
ws.on("message", (msg) => {
const msgObj = JSON.parse(msg.toString());
if (msgObj?.type) {
if (msgObj.type === "login") {
ws.userinfo = msgObj.userinfo;
}
if (msgObj?.data) {
const msgStr = ws.userinfo.username + "说:" + msgObj.data.msg;
console.log(666.10021, msgObj);
ws.send("服务器[私发]:" + msgStr);
wsServer.broadcast(msgStr);
}
}
});
ws.on("close", () => {
console.log(666.1005, "ws is closed!");
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Node.js+html5实现WebSocket服务示例</title>
</head>
<body>
<div id="show"></div>
<div>
<input id="message" type="text" style="width: 200px" />
<button type="button" id="send" onclick="sendMessage();">Send!</button>
<button type="button" id="send" onclick="exit();">exit</button>
</div>
<script>
var ws = new WebSocket("ws://localhost:9091");
ws.onopen = (e) => {
console.log("Connection to server opened" + ws.readyState);
document.getElementById("show").innerHTML =
"连接状态:" + ws.readyState + "</br>";
ws.send(
JSON.stringify({
type: "login",
userinfo: { username: 'asai' + Date.now(), password: "123456" },
})
);
ws.onmessage = (evt) => {
console.log(666.10002, evt);
document.getElementById("show").innerHTML += evt.data + "</br>";
};
ws.onclose = (evt) => {
console.log("WebSocketClosed!");
console.log(evt);
};
};
function sendMessage() {
var msg = document.getElementById("message").value;
var msgObj = { type: "message", data: { msg: msg } };
ws.send(JSON.stringify(msgObj));
document.getElementById("message").value = "";
}
function exit() {
ws.close();
console.log("退出啦");
}
</script>
</body>
</html>
原文地址:https://blog.csdn.net/qq_25753445/article/details/132498985
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_48874.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。