the chatgtp's answer
Complete code about index.html and service.js
you just need to copy it and install the model
then run the service.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="msg" id="msg">
<input type="button" value="发送" id="btn">
<ul id="showMsg"></ul>
<script>
var ws = new WebSocket("ws://localhost:8080/socket");
var btn = document.getElementById('btn')
var inputDom = document.getElementById('msg')
var ulDom = document.getElementById('showMsg')
btn.addEventListener('click', function () {
ws.send(inputDom.value)
inputDom.value = ''
})
ws.onopen = function (evt) {
console.log("Connection open ...");
//ws.send("Hello WebSockets!");
};
let liHtml = ''
ws.onmessage = function (evt) {
console.log(evt.data);
liHtml += `<li>:${evt.data}</li>`
ulDom.innerHTML = liHtml
};
ws.onclose = function (evt) {
console.log("Connection closed.");
};
ws.onerror = function () {
console.log('连接错误');
}
</script>
</body>
</html>
var express = require('express');
var ws = require('express-ws')
var router = express.Router();
var app = express();
ws(app)
ws(router); //将 express 实例上绑定 websocket 的一些方法
let wss=ws(app).getWss('/')
router.ws("/", function (ws, req) {
ws.send("你连接成功了");
ws.on("message", function (msg) {
ws.send("pong:" + msg);
wss.clients.forEach(e=>{
e.send(msg)
})
});
})
app.use('/socket', router);
app.use('/', express.static('main'));
app.listen(8080,()=>{
console.log('connecting');
}); //必须, 自己修改
The final implementation effect