webSoket--ws模块

安装

npm i --save ws

服务端

const WebSocket = require('ws')

const wss = new WebSocket.Server({
    port: 5852
})

wss.on('connection', ws => {
    console.log(`[SERVER] connection()`)

    ws.on('message', message => {
        console.log(`[SERVER] Received: ${message}`)

        ws.send(`ECHO: ${message}`, error => {
            if (error) {
                console.log(`[SERVER] error: ${error}`)
            }
        })
    })
})
运行服务端 node server.js

客户端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <input id="sendTxt" type="text">
    <button id="sendMessage">发送</button>
    <div id="infoBox"></div>
    <script>
        // 创建WebSoket对象
        var ws = new WebSocket('ws://localhost:5852')

        // 连接建立时触发
        ws.onopen = function () {
            console.log('WebSocket已连接')
            document.getElementById('infoBox').innerHTML = '已连接'
            // 使用连接发送数据
            // ws.send('hello')
        }
        
        // 客户端接收服务端数据时触发
        ws.onmessage = function (msg) {
            console.log(msg)

            // 关闭连接
            ws.close()
        }

        // 通信发生错误时触发
        ws.onerror = function (error) {
            console.log(error)
        }

        // 连接关闭时触发
        ws.onclose = function () {
            console.log('WebSocket已关闭')
        }

        // 点击按钮发送消息
        document.getElementById('sendMessage').onclick = function () {
            var txt = document.getElementById('sendTxt').value
            // 使用连接发送数据
            ws.send(txt)
            document.getElementById('infoBox').innerHTML = txt
        }
    </script>
</head>

<body>

</body>

</html>

服务端运行截图
在这里插入图片描述
文件目录截图
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值