how to use express-ws and express realize webSocket function

该文章展示了一个简单的WebSocket应用,包括一个HTML页面(index.html)用于用户交互,以及一个服务端脚本(service.js),使用Express框架和express-ws库来处理WebSocket连接。当用户在HTML页面输入消息并发送时,消息会通过WebSocket连接传递到服务器,服务器不仅回应消息,还会将消息广播给所有已连接的客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值