1.服务器端代码 app.js 需要安装 ws模块
const WebSocket = require("ws"); // 引入模块
const ws = new WebSocket.Server({ port: 3000 }, () => {
// 监听接口
console.log("socket start");
});
// 存放用户发过来的数据
let clients = {};
ws.on("connection", client => {
// 把用户发过来的数据存储到数组里面
clients.push(client);
// 初始化 返回的数据
client.send("欢迎光临");
// 监听 客户端发送的消息
client.on("message", msg => {
console.log("来自服务器的数据", msg, clients);
client.send(msg); // 通过send方法来给前端发送消息
//sendall();
});
// 监听关闭事件
client.on("close", msg => {
console.log("关闭服务器连接");
});
});
2.客户端代码 index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1></h1>
<br>
<input type="text" id="sendtext">
<button onclick="send()">send</button>
<script>
const ws = new WebSocket("ws://localhost:3000/") // 监听地址端口号
// 链接 服务器
ws.onopen = function () {
console.log("服务器连接")
}
// 监听服务器返回内容
ws.onmessage = (msg) => {
console.log("来自服务器发来的数据" + msg.data)
console.log("来自服务器msg", msg)
alert("服务器返回内容:" + msg.data)
}
// 监听 页面websocket关闭事件
ws.onclose = () => {
console.log("服务器关闭")
}
// 获取数据 发送到 websocket 到服务器
function send() {
//alert()
let msg = document.getElementById("sendtext").value;
// 发送到 服务器
ws.send(msg)
}
</script>
</body>
</html>
发表评论