效果图
页面代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>WebSocket Client</title></head><body><script>const ws = new WebSocket('ws://localhost:8765')ws.onopen = () => {console.log('HTML: init!')ws.send(`HTML say -> I'm init!`)}ws.onmessage = event => {console.log('HTML listen: ', event.data)}ws.onerror = error => {console.error('HTML Error: ', error)}ws.onclose = event => {if (event.wasClean) {console.log('HTML Closed cleanly, code:',event.code,'reason:',event.reason)} else {console.error('HTML Connection died')}}</script></body>
</html>
服务后台代码
const WebSocket = require('ws')const wss = new WebSocket.Server({ port: 8765 })wss.on('connection', ws => {console.log('SERVER: init!')ws.on('message', message => {console.log('SERVER listen: %s', message)setInterval(() => {function getTwoNum(num) {return (+num < 10 ? '0' : '') + num}const now = new Date()const nowStr = `${now.getFullYear()}-${getTwoNum(now.getMonth() + 1)}-${getTwoNum(now.getDate())} ${getTwoNum(now.getHours())}:${getTwoNum(now.getMinutes())}:${getTwoNum(now.getSeconds())}`ws.send(`SERVER say -> ${nowStr}`)}, 3000)})
})
new WebSocket() api说明
var Socket = new WebSocket(url, [protocol] );
参数:
- url, 指定连接的 URL
- protocol 是可选的,指定了可接受的子协议
属性:
- Socket.readyState 只读属性 readyState 表示连接状态(0-表示连接尚未建立; 1-表示连接已建立,可以进行通信; 2-表示连接正在进行关闭; 3-表示连接已经关闭或者连接不能打开)
- Socket.bufferedAmount 只读属性 bufferedAmount 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数。
事件:
- open Socket.onopen 连接建立时触发
- message Socket.onmessage 客户端接收服务端数据时触发
- error Socket.onerror 通信发生错误时触发
- close Socket.onclose 连接关闭时触发
方法:
- Socket.send() 使用连接发送数据
- Socket.close() 关闭连接