安装websocket:npm i ws
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const ws = new WebSocket("ws://localhost:3000")
ws.addEventListener("open", () => {
console.log("客户端连接上服务端了");
//建立连接,发送请求给websocket
ws.send("客户端向服务端发送消息,你好啊")
})
ws.addEventListener("message", (data) => {
console.log("服务端给客户端的回应:", data.data)
})
</script>
</body>
</html>
服务端代码
const websocket = require("ws");
const wss = new websocket.Server({ port: 3000 })
wss.on("connection", ws => {
console.log("建立连接")
ws.on("close", () => {
console.log("断开连接")
})
ws.on("message", data => {
// console.log(data)
//接收客户端发送的消息处理一下返回给客户端
ws.send("res:" + data)
})
})
最终效果