简单的来说,websocket是用来实现客户端和服务端进行双向连接的,连接之后,服务器可以给客户端主动发数据
前端
<!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>
<script>
let websocket = null;
window.onload = function () {
if ("WebSocket" in window) {
websocket = new WebSocket("ws://127.0.0.1:3000");
websocket.onopen = (e) => {
console.log("websocket is connection", e);
};
websocket.onmessage = (e) => {
console.log("message被触发", e);
};
websocket.onclose = (e) => {
console.log("websocket is closed\r\n", e);
};
websocket.onerror = (e) => {
console.log("websocket is error\r\n", e);
};
}else{
console.error("您的浏览器不支持websocket,请更换浏览器再试")
}
};
function send() {
console.info("我要发消息拉");
websocket.send("hello");
}
</script>
</head>
<body>
<button onClick="send()">发送消息</button>
</body>
</html>
后端
"use strict";
const ws = require('nodejs-websocket')
const server = ws.createServer(function(con){
console.log("new connection")
con.on('text', str=>{
console.log('receiving \r\n', str)
con.sendText('收到'+str+'!!!!')
})
setInterval(()=>{
send()
},3000)
con.on('close', (code,reason)=>{
console.log('connection is closed\r\n',code, reason)
})
con.on("error",e=>{
console.log("error=\r\n",e)
})
})
function send(){
server.connections.forEach(connection=>{
connection.sendText('hahah')
})
}
server.listen(3000,()=>{
console.info('ws is running at:\r\n ws://127.0.0.1:3000')
})
socket.io
优点:可以利用http进行websocket通信,可以自定义事件分发
前端
<!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>
<script src="https://cdn.bootcdn.net/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
<script>
let socket = null
window.onload = function(){
socket = io('http://127.0.0.1:3000')
socket.on('connect',()=>{
console.log("成功链接服务端啦")
})
socket.on('disconnect',()=>{
console.log("服务断开,尝试重新链接")
socket.connect()
})
socket.on('msg',(data)=>{
console.log('收到msg',data)
})
}
function send(){
if( !socket ) {
console.error("还没有链接")
}else{
console.log("开始发数据")
socket.emit('text','客户端发来数据')
}
}
function hello(){
if(!socket){
console.error("还没有链接")
}else{
console.log("发送hello事件")
socket.emit('hello','world')
}
}
</script>
</head>
<body>
<button onclick='send()'>发送消息</button>
<button onclick='hello()'>hello</button>
</body>
</html>
后端
const server = require('http').createServer();
const io = require('socket.io')(server, { cors: true });
io.on('connection', client => {
console.log("有人链接了\r\n")
client.on('event', data => {
console.log('event\r\n', data)
});
client.on('disconnect', () => {
console.log('client is disconnected\r\n')
});
client.on('hello',(data)=>{
console.log("hello事件被触发,收到数据",data)
})
client.on('text',(data)=>{
console.log('text事件被触发',data)
})
});
server.listen(3000);
|