1.什么是websocket?
webrtc能更好的处理流文件。直播用的就是webrtc。
2.websocket通信原理
3.websocket服务端与客户端通信实现
3.1 npm install websocket-node
服务端 index.js
var WebSocket= require('websocket').server
var http = require('http')
var httpServer = http.createServer().listen(8080, function(){
console.log('http://127.0.0.1:8080')
})
var wsServer = new WebSocket({
httpServer: httpServer,
autoAcceptConnections: false,
})
var conArr = []
wsServer.on('request', function(request) {
var connection = request.accept()
conArr.push(connection)
connection.on('message', function(msg) {
console.log('msg', msg)
for(var i = 0; i < conArr.length; i++) {
conArr[i].send(msg.utf8Data)
}
})
})
启动服务器:node index.js 在浏览器中打开打开
客户端 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>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text"/>
<input type="button" value="发送" onclick="send()">
<script>
var websocket = new WebSocket('ws://127.0.0.1:8080')
websocket.onopen = function() {
}
function send() {
var text = document.getElementById('text').value
websocket.send(text)
}
websocket.onmessage = function(back) {
console.log('back', back, back.data)
}
</script>
</body>
</html>
3.2 socketio
https://socket.io/docs/v4/handling-cors/ npm install socket.io@4.1.2 index.js
const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"],
}
});
io.on("connection", (socket) => {
socket.on('sendMsg', (data) => {
console.log(data)
io.emit('pushMsg', text)
})
});
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.2.0/socket.io.min.js"></script>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text"/>
<input type="button" value="发送" onclick="send()">
<script>
var socket = io.connect('http://127.0.0.1:3000')
function send() {
var text = document.getElementById('text').value
socket.emit('sendMsg', text)
}
socket.on('pushMsg', (data) => {
console.log('data', data)
})
</script>
</body>
</html>
跨域遇到的2种问题: 1.浏览器阻止发送请求 2.浏览器正常发送请求,服务端也接受请求并作出响应,但是浏览器拒绝服务器的数据响应
2种表现形式: 1.简单请求 2.需预检请求(复杂请求)
|