WebSocket的定义
WebSocket是html5提供的一种在单个TCP连接上进行双向通信的协议,解决了客户端和服务端之间的实时通信问题。浏览器和服务器只需完成一次握手,两者之间就可以创建一个持久性的TCP连接,此后服务器和客户端通过此TCP连接进行双向实时通信。
1、创建一个socket.js文件,用于多个地方调。
const URL = "ws://ws.xxxxxx.com:2000"
function SocketTask() {
let socketOpen = false
let ws = new WebSocket(URL);
this.open = (callback) => {
ws.onopen = () => {
this.socketOpen = true
}
}
this.send = (data) => {
ws.send(JSON.stringify(data))
}
this.receiveMsg = (callback) => {
ws.onmessage = (e) => {
callback(e)
}
}
this.close = () => {
ws.onclose = () => {
this.socketOpen = false
}
}
}
2、引用 3、使用websocket
let socketTask = null
window.onload = () => {
initSocket()
}
function initSocket() {
socketTask = new SocketTask()
socketTask.open()
handleSend()
receiveMsg()
}
function handleSend() {
let data = {id: '1'}
if(socketTask.socketOpen) {
socketTask.send(data)
}else{
setTimeout(() => {handleSend()}, 1000)
}
}
function receiveMsg () {
socketTask.receiveMsg((res) => {
console.log('res:', res)
})
}
|