webSocket 基本使用

it2025-09-17  4

后端

安装 webSocket

npm i ws

创建对象

const webSocket = require('ws') const wss = new webSocket.Srever({ port: 9998 })

监听事件

连接事件

wss.on("connection", client=>{ console.log('有客户端连接。。。') })

接收数据事件

wss.on("connection", client=>{ client.on("message", msg=>{ console.log('客户端发送过来的数据') }) })

发送数据

client.send('发送数据给前端端')

示例

// 使用websocket // 1 导入WebSocket模块 const WebSocket = require('ws') // 2 创建websocket 服务对象 绑定端口8889 const wss = new WebSocket.Server({port:8889}) // 3 事件监听 连接事件 wss.on('connection', client=>{ // 监听客户端发送的数据 client.on('message', msg=>{ console.log('msg',msg) // 由服务端发送数据到服务端 client.send('hello socket backed data') }) })

前端

创建对象

const ws = new WebSocket('ws://localhost:9998')

监听事件

连接成功事件

ws.onopen = function(){}

接收数据事件

ws.onmessage = function(){}

关闭连接事件

ws.onclose = function(){}

发送数据

wx.send()

示例

<!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> <button id="connection">连接 服务端</button> <button id="send" disabled>发送数据</button> 从服务端接收数据:<br> <span id='text'></span> <script> const connection = document.getElementById('connection') const send = document.getElementById('send') const text = document.getElementById('text') let ws = null // 建立连接 connection.onclick = function(){ ws = new WebSocket('ws://localhost:8889') ws.onopen = function(){ console.log('连接成功') send.disabled = false } // 监听 服务端向客户端发送数据事件 ws.onmessage = function(msg){ console.log('接收数据',msg.data) } ws.onclose = function(){ console.log('断开连接') send.disabled = true } } // 发送数据 send.onclick = function(){ ws.send('发送数据') } </script> </body> </html>
最新回复(0)