const WebSocket = require('ws');
const http = require('http');
// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
// 设置允许跨域请求
res.setHeader('Access-Control-Allow-Origin', 'http://10.100.33.73:8090');
// 允许带凭据的请求
res.setHeader('Access-Control-Allow-Credentials', 'true');
// 其他CORS头部也可以根据需要设置
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
// 处理预检请求
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// 处理其他HTTP请求
res.writeHead(404);
res.end();
});
// 创建WebSocket服务器,将其附加到HTTP服务器
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
// 每隔5秒向客户端发送消息
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(`{
"eventName": "eventValue",
"data": "#A1"
}`);
}
}, 5000);
// 接收客户端发送的消息
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
// 发送消息给客户端
//ws.send('Server received your message');
});
// 当连接关闭时触发
ws.on('close', () => {
console.log('Client disconnected');
});
});
// 启动HTTP服务器
const PORT = process.env.PORT || 8085;
console.log(process.env.PORT,'bocaige')
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
---------------------------------------------------------------------------------------------------------------------