基本介绍
- WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输 。 
简易聊天室实现
- 思路

前端实现
事件
- open : 连接建立时触发
- message: 客户端接收服务端数据时触发
- error: 通信发生错误时触发
- close: 连接关闭时触发
步骤
- 目录文件
 - entry.html
<!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>
<div>
用户名: <input id="userName" type="text" placeholder="请输入用户名">
</div>
<div>
密码: <input id="passWord" type="text" placeholder="请输入密码">
</div>
<button id="btn">登入</button>
<script src="./js/entry.js"></script>
</body>
</html>
登录跳转
((doc, location) => {
const useName = doc.querySelector('#userName')
const passWord = doc.querySelector('#passWord')
const btn = doc.querySelector('#btn')
const init = () => {
bindEvent()
}
function bindEvent() {
btn.addEventListener('click', handClick, false)
}
function handClick () {
console.log('useName', useName, useName.value)
console.log('passWord',passWord, passWord.value )
if ( useName.value && passWord.value) {
location.href = 'index.html?useName='+ useName.value + '&passWord='+ passWord.value
}
}
init ()
})(document, location)
<!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>
<ul id="list"></ul>
<input id="message" type="text" placeholder="请输入消息">
<button id="send">发送</button>
<script src="./js/index.js"></script>
</body>
</html>
绑定各种事件
((doc) => {
const oList = doc.querySelector('#list')
const oMsg = doc.querySelector('#message')
const oSendbtn = doc.querySelector('#send')
const ws = new WebSocket('ws:localhost:8000')
let userName = ''
let passWord = ''
const init = () => {
let url = location.search
if (url.indexOf('?') !== -1) {
let str = String(url).slice(0)
let arr = str.split('&')
userName = arr[0].split('=')[1]
passWord = arr[1].split('=')[1]
console.log('userNamepassWord', userName, passWord)
}
bindEvent()
}
function bindEvent() {
oSendbtn.addEventListener('click', handSend, false)
console.log('ws', ws)
ws.addEventListener('open', handleOpen, false)
ws.addEventListener('close', handleClose, false)
ws.addEventListener('error', handleError, false)
ws.addEventListener('message', handleMessage, false)
}
function handSend (e) {
const msg = oMsg.value
if (!msg.trim().length) {
return
}
ws.send(JSON.stringify({
user: userName,
passsword: passWord,
msg,
dateTime: new Date()
}))
console.log('send', e)
oMsg.value = ''
}
function handleOpen (e) {
console.log('open', e)
}
function handleClose (e) {
console.log('close', e)
}
function handleError (e) {
console.log('error', e)
}
function handleMessage (e) {
console.log('message', e)
const msgData = JSON.parse(e.data)
console.log('msgData', msgData)
oList.appendChild(createMsg(msgData))
}
function createMsg(data) {
const {user, msg, dateTime} = data
const oItem = doc.createElement('li')
oItem.innerHTML = `
<p>
<span>${user}</span>
<i>${dateTime}</i>
</p>
<p>消息:${msg}</p>
`
return oItem
}
init()
})(document)
后端实现
事件
- open : 连接建立时触发
- message: 客户端接收服务端数据时触发
- error: 通信发生错误时触发
- close: 连接关闭时触发
- connection: 监测websocket连接
步骤
  index.js
绑定事件开启服务
const Ws = require('ws').Server
;((Ws) => {
const server = new Ws({
port: 8000
})
const init = () => {
bindEvent()
}
function bindEvent () {
server.on('open', handleOpen)
server.on('close', handleClose)
server.on('error', handleError)
server.on('connection', handleConnection)
}
function handleOpen (ws) {
console.log('server open')
}
function handleClose (ws) {
console.log('server close')
}
function handleError (ws) {
console.log('server error')
}
function handleConnection (ws) {
console.log('server connection')
ws.on('message', handleMessag)
}
function handleMessag (msg) {
console.log('msg', msg.toString())
server.clients.forEach(c => {
c.send(msg.toString())
})
console.log(server.clients)
}
init()
})(Ws)
效果
 
|