基于 websocket-node实现
新建项目websocket-node
mkdir websocket-node
进入目录
cd websocket-node
初始化项目
npm init -y
下载依赖
npm install websocket@1.0.34
新建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)
for(let i=0;i<conArr.length;i++){
conArr[i].send(msg.utf8Data) // 向所有连接发送消息
}
})
})
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<input id="text" type="text">
<input type="button" value="发送" onclick="send()">
</body>
<script>
var websocket = new WebSocket('ws://127.0.0.1:8080');
// readyState 4种状态 0:链接正在建立 1:链接建立成功 2:链接正在关闭 3:链接关闭成功
websocket.onopen = function(){
console.log(websocket.readyState)
}
function send(){
var text = document.getElementById('text').value;
websocket.send(text) // 向服务器发送消息
}
websocket.onmessage = function(back){ // 监听服务器推送事件
console.log(back.data)
}
</script>
</html>
基于sockrt.io实现
同上新建项目,安装依赖
npm install socket.io@4.1.2 // 注意版本!
服务端代码
const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "*", // socket.io需要配置跨域
methods:["GET","POST"]
}
});
io.on("connection", (socket) => {
socket.on('sendMsg', (data)=>{
// console.log(data)
// socket.emit('pushData',data) // 向单个连接发送消息
io.emit('pushData',data) // 向所有连接发送消息
})
});
httpServer.listen(3000, function(){
console.log('http://127.0.0.1:3000')
});
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<!-- cdn方式引入 socket.io -->
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js" integrity="sha384-7EyYLQZgWBi67fBtVxw60/OWl1kjsfrPFcaU0pp0nAh+i8FD068QogUvg85Ewy1k" crossorigin="anonymous"></script>
</head>
<body>
<input id="text" type="text">
<input type="button" value="发送" onclick="send()">
</body>
<script>
var socket = io.connect('http://127.0.0.1:3000');
function send(){
var text = document.getElementById('text').value;
socket.emit('sendMsg',text) // 向websocket服务器发送消息
}
socket.on('pushData', function(back){ // 监听服务器消息推送
console.log(back)
})
</script>
</html>
更推荐使用socket.io的方式,不需要手动处理连接池。