Socket.io 404 error

前端 未结 4 1592
心在旅途
心在旅途 2020-12-22 04:12

I have followed Jeffrey way\'s tutorial.
Tutorial:
https://laracasts.com/series/real-time-laravel-with-socket-io/episodes/1

this is my index.js



        
相关标签:
4条回答
  • 2020-12-22 04:59

    Your server is listening on port 3000, but the socket.io URL you show is port 8888. If you do have some other server running on port 8888 (perhaps your PHP server), it's not this one that's running socket.io.

    To understand exactly what fix is needed, this raises a question about what's the URL of the page you show the HTML for? What does the browser show in the URL bar when you display that page? Your node.js code implies you're intending to load that page from the port 3000 node.js server, but the client code you show would not be loading it from port 8888 if that's the case.

    0 讨论(0)
  • 2020-12-22 05:04

    Try doing this code.

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    app.get('/', function(req, res) {
        res.sendfile('index.html');
    });
    
    users = [];
    io.on('connection', function(socket) {
        console.log('A user connected');
        socket.on('setUsername', function(data) {
            console.log(data);
    
            if(users.indexOf(data) > -1) {
                socket.emit('userExists', data + ' username is taken! Try some other username.');
            } else {
                users.push(data);
                socket.emit('userSet', {username: data});
            }
        });
    
        socket.on('msg', function(data) {
            //Send message to everyone
            io.sockets.emit('newmsg', data);
        })
    });
    
    http.listen(3000, function() {
       console.log('listening on localhost:3000');
    });
    

    Let me know if it works.

    0 讨论(0)
  • 2020-12-22 05:04

    I'm adding this because this comes up first on Google and it took me 2 days to find a solution.

    I'm using Node.js and React, with socket.io-client

    I was able to make it work by passing a url and a configuration object to the io namespace.

    import io from 'socket.io-client'
    const socket = io('http://localhost:3000', {
        reconnectionDelay: 1000,
        reconnection: true,
        reconnectionAttemps: 10,
        transports: ['websocket'],
        agent: false,
        upgrade: false,
        rejectUnauthorized: false
    });
    
    0 讨论(0)
  • 2020-12-22 05:11

    I am almost sure Marlon´s code worked because http.listen is at the end of index.js

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