Skip to content
Advertisement

Laravel socket.io doesn’t work, failed socket connect, how to fix?

I am trying to create a live chat. Socket.io and node.js I can’t connect the user to my channel. https://domen.com:8005/socket.io/?EIO=3&transport=polling&t=NYHmcgH :failed

Here is my server.js

var app = require('express')();
var https = require('https').Server(app);
var io = require('socket.io')(https);
var Redis = require('ioredis');
var redis = new Redis();
var users = [];

https.listen(8005, function () {
    console.log('Listening to port 8005');
});

io.on('connection', function (socket) {
    socket.on("user_connected", function (user_id) {
        console.log("user connected " + user_id);
        // users[user_id] = socket.id;
        // io.emit('updateUserStatus', users);
        // console.log("user connected "+ user_id);
    });

and here is my blade template

    <script>
            $(function () {
                let user_id = "{{ auth()->user()->id }}";
                console.log(user_id);
                let ip_address = 'domen.com';
                let socket_port = '8005';
                let socket = io(ip_address + ':' + socket_port);
            });
    
      socket.on('connect', function () {
                    socket.emit('user_connected', user_id)
                });
</script>

Advertisement

Answer

express with https needs some keys

var https = require('https')
var app = express()

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app)
.listen(8005, function () {
  console.log('Example app listening on port 8005! Go to https://domen.com:3000/')
})

i think you should try first with http, if your code works well then you can upgrade to https

var io = require('socket.io')(http);
http.listen(8005, function () {
    console.log('Listening to port 8005');
});

in client side :

let ip_address = 'http://domen.com';
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement