js ====>node wstest.js
var ws = require('nodejs-websocket');
const PORT = 3000;
var server = ws.createServer((conn) => {
console.log("链接成功");
conn.on("error",()=>{
console.log("error")
});
conn.on("close",()=>{
console.log("连接关闭")
});
conn.on("text",(data)=>{
conn.send(`你好~~${data.toUpperCase()}`);
});
})
server.listen(PORT,()=>{
console.log("服务启动成功,监听了端口" + PORT);
})
html 文件
<!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>
<input type="text" placeholder="请输入内容" />
<button>发送请求</button>
<div></div>
</body>
<script>
var input = document.querySelector('input');
var button = document.querySelector("button");
var div = document.querySelector("div");
var socket = new WebSocket("ws://127.0.0.1:3000");
socket.addEventListener("open",()=>{
div.innerHTML = "连接成功";
})
button.addEventListener('click',()=>{
var value = input.value;
socket.send(value);
input.value = '';
})
socket.addEventListener('message',(e)=>{
var dv = document.createElement("div");
dv.innerHTML = e.data;
div.appendChild(dv);
})
</script>
</html>