skip to Main Content

I’ve encountered an error with other people’s computers, they can’t access my little test chatting application, and incounter this error when attempting to connect:

localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1
       
       
        Failed to load resource: net::ERR_CONNECTION_REFUSED
localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2KorJ:1

My socket.io version is: 4.7.2 and I’m port fowarding with ngrok, i’ve tried localtunnel, same errors as ngrok. Not sure why I’m also getting strict-origin-when-cross-origin for some reason I even have my origin set as "*" so it’s very weird. Here is my code:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    },
    transports: ['websocket']
});

mongoose.connect('notgonnagiveyouthat', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const PORT = 3000;

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

const User = mongoose.model('User', userSchema);

const messageSchema = new mongoose.Schema({
    username: String,
    content: String,
    timestamp: {
        type: Date,
        default: Date.now
    }
});

const Message = mongoose.model('Message', messageSchema);

passport.use(new LocalStrategy(async (username, password, done) => {
    try {
        const user = await User.findOne({ username: username });
        if (!user) {
            return done(null, false, { message: 'Username not registered' });
        }
        const isMatch = await bcrypt.compare(password, user.password);
        if (isMatch) {
            return done(null, user);
        } else {
            return done(null, false, { message: 'Incorrect password' });
        }
    } catch (err) {
        return done(err);
    }
}));

passport.serializeUser((user, done) => {
    done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
    try {
        const user = await User.findById(id);
        done(null, user);
    } catch (err) {
        done(err);
    }
});

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(express.urlencoded({ extended: false }));

app.get('/login', (req, res) => {
    res.sendFile(__dirname + '/login.html');
});

app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login'
}));

app.get('/signup', (req, res) => {
    res.sendFile(__dirname + '/signup.html');
});

app.post('/signup', async (req, res) => {
    const { username, password } = req.body;
    const user = await User.findOne({ username });
    if (user) {
        return res.redirect('/signup');
    }
    const hashedPassword = await bcrypt.hash(password, 10);
    const newUser = new User({
        username,
        password: hashedPassword
    });
    await newUser.save();
    res.redirect('/login');
});

app.get('/', (req, res) => {
    if (!req.isAuthenticated()) {
        return res.redirect('/login');
    }
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', async (socket) => {
    console.log('User connected');
    try {
        const messages = await Message.find().sort({ timestamp: -1 }).limit(10).exec();
        socket.emit('previousMessages', messages.reverse());
    } catch (err) {
        console.error("Error fetching messages:", err);
    }
    socket.on('sendMessage', async (data) => {
        const message = new Message({
            username: data.username,
            content: data.content
        });
        try {
            await message.save();
            io.emit('receiveMessage', message);
        } catch (err) {
            console.error("Error saving message:", err);
        }
    });
    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

2

Answers


  1. That is because their application is trying to connect to "localhost" that resolves to 127.0.0.1, which is their local machine address. You want their client app to try to connect to your machine IP address instead. To find your local IP address you can follow this question: https://apple.stackexchange.com/questions/20547/how-do-i-find-my-ip-address-from-the-command-line

    Login or Signup to reply.
  2. The "net::ERR_CONNECTION_REFUSED" error in Socket.io typically occurs when the client is unable to establish a connection with the server. This error can be caused by various factors, such as incorrect server configuration, network issues, or firewall restrictions.

    To troubleshoot this issue when accessing Socket.io from different devices, you can follow these steps:

    1. Check the server configuration: Ensure that the server is running and listening on the correct IP address and port. Double-check the server code to make sure it is correctly configured to accept connections from different devices.

    2. Verify network connectivity: Ensure that both the client and server devices are connected to the same network or have proper internet connectivity. Check if there are any network issues or firewall restrictions that might be blocking the connection.

    3. Check firewall settings: If you have a firewall enabled on the server or client devices, make sure it allows incoming and outgoing connections on the specified port used by Socket.io (usually port 80 or 443 for HTTP/HTTPS).

    4. Test with different devices: Try accessing the Socket.io server from different devices (e.g., smartphones, tablets, or other computers) connected to the same network. This will help determine if the issue is specific to a particular device or network configuration.

    5. Use the correct server URL: Ensure that the client is using the correct URL to connect to the Socket.io server. The URL should include the correct IP address or domain name of the server, along with the port number if it is different from the default (e.g., http://your-server-ip:3000).

    By following these steps, you should be able to identify and resolve the "net::ERR_CONNECTION_REFUSED" error when accessing Socket.io from different devices.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search