2022-12-18/19
简单的实现
服务器端
let Websockket = require('websocket').server
let http = require('http')
let httpServer = http.createServer().listen(8080, function(){
console.log("http://127.0.0.1:8080")
})
let wsServer = new Websocket({
httpServer: httpServer,
autoAcceptConnections: false
})
let conArr = [];
wsServer.on('request', function(request){
let connection = request.accept();
//每次建立,connection都不一样,每次建立一个,都保存一个
conArr.push(connection)
connection.on('message', function(){//接收客户端消息
console.log(msg) // {type:'utf', utf8Data: 'inputvalue'}
for(let i = 0; i < conArr.length; i++){
// 当前连接给客户端发消息
conArr[i].send(msg.utf8Data)
}
})
})
客户端,省去了html,只有核心代码
let websocket = new WebSocket('ws://127.0.0.1:8080')
//调用websocket 对象建立连接
//参数: ws/wss(加密)//ip:port (字符串)
//readyState
//0 连接还没有建立,正在建立连接
//1 连接建立成功
//2 连接正在关闭
//3 连接已经关闭
//onopen 监听连接打开
websocket.onopen = function() {
console.log(websocket.readyState) // 1
}
function send(){
let text = document.getElementById('text').value
websocket.send(text); //给服务端发消息
}
//绑定服务端推送到客户端的监听事件
websocket.onmessage = function(back){
console.log(back);//Object : MessageEvent
//服务器推送过来的数据
console.log(back.data)
}
//监听连接关闭
websocket.onclose = function (evt){}
//监听连接错误信息
websocket.omerror = function(evt, e){}
建立多个客户端,每次建立一个,都会和服务器建立一个连接
每一个客户端和服务器建立连接之后,每一个连接都有不同的标识(会话id)
part2 socket.io
查看文档 socket.io/docs/v4/
npm install socket.io
写服务器 index.html
const { createServer } = require('http')
const { Server } = require('socket.io')
const httpServer = createServer()
const io = new Server(httpServer, {
/* options */
//跨域处理
cors: {
origin: '*',
},
})
io.on('connection', (socket) => {
// ...
socket.on('sendMsg', (data) => {
console.log(data)
//广播
io.emit('pushMsg', data)
})
})
httpServer.listen(3000, function () {
console.log('http://127.0.0.1:3000')
})
客户端 index.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>
<script
src="https://cdn.socket.io/4.4.1/socket.io.min.js"
integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H"
crossorigin="anonymous"
></script>
</head>
<body>
<input type="text" id="text"></input>
<input type="button" value="发送" onclick="send()"></input>
<script>
var socket = io.connect('http://127.0.0.1:3000');
function send(){
let text = document.getElementById('text').value
socket.emit('sendMsg', text); //给服务端发消息
}
socket.on('pushMsg', data => {
console.log(data)
})
</script>
</body>
</html>
跨域link: zhuanlan.zhihu.com/p/53996160
课堂文档截图: