【问题标题】:Working socket.io demo getting error message with工作 socket.io 演示收到错误消息
【发布时间】:2022-01-29 12:49:35
【问题描述】:

我一直在寻找不使用 Express.js 的 socket.io 的工作演示,为什么这个示例不起作用:

服务器:

const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
  client.on('event', data => { /* … */ });
  client.on('disconnect', () => { /* … */ });
});
server.listen(3000);

客户:

<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
<script>
  const socket = io("http://localhost");
</script>

这给出了错误: polling-xhr.js:157 GET http://localhost/socket.io/?EIO=4&transport=polling&t=NwWVGV9 net::ERR_CONNECTION_REFUSED

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    找到一些有用的东西:

    服务器:

    var app = require('http').createServer(handler);
    var io = require('socket.io')(app);
    var fs = require('fs');
    
    app.listen(80);
    
    function handler(req, res) {
        var url;
        if (req.url == "/") {
            url = "/index.html";
        } else {
            url = req.url;
        }
        fs.readFile(__dirname + url, function (err, data) {
            if (err) {
                res.writeHead(404);
                res.end(JSON.stringify(err));
                return;
            }
            res.writeHead(200);
            res.end(data);
        });
    }
    
    io.on('connection', function (socket) {
        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data) {
            console.log(data);
        });
        socket.on('disconnect', function () {
            console.log(socket.id + ' disconnect ('+ socket.client.conn.transport.constructor.name +')');
        });
    });
    

    客户:

    <script src="node_modules/socket.io/client-dist/socket.io.min.js"></script>
    <script>
      var socket = io();
      socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
      });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多