socket.io - can't get it to work, having 404's on some kind of polling call

后端 未结 3 1706
闹比i
闹比i 2020-12-08 13:20

I\'m trying to get a server set up with socket.io, with bad results.

I am mostly following this guide, although it\'s somewhat out of date: http://www.williammora.co

相关标签:
3条回答
  • 2020-12-08 13:49

    Just for check that is your server or just client problem you could use this web: websocket-echo, if this client connect right to your server (the first form client is usefull if your server is online, if is on your host, cuoting from websocket.org...

    Using a text editor, copy the following code and save it as websocket.html somewhere on your hard drive

    Code: websocket-test

    The only thing different from mine that i could observe is the io client source: <script src="/socket.io/socket.io.js"></script> on your client side.

    On your server you should try this way:

    var express = require('express'), 
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server),
    exec = require('child_process').exec,
    util = require('util');
    
    //serve our code
    app.use(express.static('public'));
    app.use(express.json());
    app.use(express.urlencoded());
    //listening on connections
    
    io.on('connection', function (socket) {
        console.log('client connected!'); 
    }
    server.listen(8080);
    

    Note that this way works fine with this dependencies: I recommend you add this code below to your package.json file:

    "dependencies": {
        "express": "3.x.x",
        "socket.io": "*",
        "util": "*"
      }
    

    cheers!

    0 讨论(0)
  • 2020-12-08 13:55

    In my case, I created my app with the Express application generator. To solve this problem, instead of edit the app.js file on the root folder of the project, I edited the file bin/www on the line after the server is defined:

    /**
     * Create HTTP server.
     */
    
    var server = http.createServer(app);
    var io = require('socket.io')(server); // Add this here
    

    Update

    I found a better way here Express Generator and Socket.io

    0 讨论(0)
  • 2020-12-08 13:59

    It looks like Socket.IO can't intercept requests starting with /socket.io/. This is because in your case the listener is app -- an Express handler. You have to make http be listener, so that Socket.IO will have access to request handling.

    Try to replace

    app.set( "ipaddr", "127.0.0.1" );
    app.set( "port", 8080 );
    

    with

    http.listen(8080, "127.0.0.1");
    

    See docs for details: http://socket.io/docs/#using-with-express-3/4

    0 讨论(0)
提交回复
热议问题