美文网首页
sockit-io 允许跨域

sockit-io 允许跨域

作者: EnjoyWT | 来源:发表于2024-04-07 16:26 被阅读0次
    1. 使用http 模块创建服务
    const http = require('http');
    const { Server } = require('socket.io');
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    });
    
    const io = new Server(server, {
      cors: {
        origin: "http://localhost:3000",  // 允许本地访问
       // origin: "*",  // 允许所有
        methods: ["GET", "POST"]
      }
    });
    
    io.on('connection', (socket) => {
      console.log('a user connected');
    });
    
    server.listen(3000, () => {
      console.log('server is running on port 3000');
    });
    
    H5 测试页面
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Socket.io Example</title>
    </head>
    <body>
      <h1>Socket.io Example</h1>
    
      <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
      <script>
        const socket = io("http://localhost:3000", { transports: ['websocket'] });
    
        socket.on('connect', () => {
          console.log('Connected to server');
        });
    
        socket.on('disconnect', () => {
          console.log('Disconnected from server');
        });
      </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:sockit-io 允许跨域

          本文链接:https://www.haomeiwen.com/subject/icctxjtx.html