实现socket的方式
1.net
2.socket.io 麻烦 兼容性最好
3.websocket h5新增 低版本浏览器不兼容 使用方式简单
前端后端链接
1.搭建 websocket 服务器 new WebSocket.server({prot:8080},(=>{})) ws.on(‘connection’) 监听
2.前端进行连接 new WebSocket(‘ws://localsocket:8080’) ws是WebSocket协议 ws.onOpen(‘ok’) 监听
数据交互
client.on(‘message’,()=>{}) 一旦有数据传到服务器端就会触发这个
ws.onmessage=()=>{} 前端监听服务器端发送的数据
client.send() 服务端主动给前端发送数据
ws.send(‘nihao你好啊’) 客户端向服务端发送信息
3.前端主动发送数据
4.后端主动发送数据
5.断开链接
前后端断开的处理
ws.on('colse)
ws.onClose()
实时刷新用长连接 服务器端发起数据也用 如:短信提醒
例:1.首先是server.js服务端
先下载websocket模块 npm install ws --save
const WebSocket = require('ws')
const ws = new WebSocket.Server({port:8080},()=>{
console.log('socket start')
})
//每当有客户端链接的时候 就会有一个client对象
ws.on('connection',(client)=>{
//主动向前端发送消息
client.send('欢迎光临,我是socket发送的') //数据只能传输字符串
client.on('message',(msg)=>{
console.log('来自前端的数据:'+msg) //msg可以通过 msg.toString() 或者''+msg转换为字符串
})
client.on('close',(msg)=>{
console.log('前端主动断开了链接:' )
})
})
2.客户端
<!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">
<button onclick="sendserver()">send server</button>
<script>
const ws = new WebSocket('ws://localhost:8080/')
ws.onopen=()=>{
console.log('服务器已连接')
}
ws.onmessage=(msg)=>{
console.log('来自服务器端的数据:'+msg.data) //监听接受来自服务端的信息
}
ws.onclose=()=>{
console.log('服务器关闭')
}
function sendserver(){
ws.send('nihao你好啊') //向服务端发送信息
}
</script>
</body>
</html>