简体   繁体   中英

nodejs, socket, https - Socket makes no connection but only disconnects

I've been through A LOT of issues in here about this topic but so far no answers has been the solution for my problem.

My setup is an AWS EC2 server with apache installed. I've installed node.js in the /node folder containing a server-file called server.js and in the root folder I have my client-file index.php . I have Let´s Encrypt SSL-certificates for my domain and therefore I need everything to run over https. I have opened up the port 3000 for all traffic en AWS.

Server.js

const app = require('express')();
const fs = require('fs');

const options = {
    key: fs.readFileSync("/etc/letsencrypt/live/example.com/privkey.pem"),
    cert: fs.readFileSync("/etc/letsencrypt/live/example.com/fullchain.pem")
};

const http = require('https').Server(options, app);
const io = require('socket.io')(http);


io.on('connection', (socket) => {
  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
  });
});

http.listen(3000, function(){
    console.log('listening on 3000');
});

index.php

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket Test</title>
</head>
<body>
    <ul id="events"></ul>

    <script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
    <script>
        const events = document.getElementById('events');

        const newItem = (content) => {
            const item = document.createElement('li');
            item.innerText = content;
            return item;
        };

        const socket = io('https://example.com:3000', {transports: ['websocket', 'polling']});
        
        console.log(socket);
    
        socket.on('connect', () => {
            console.log("did connect");
            events.appendChild(newItem('connect'));
        });
        
        socket.on('disconnect', () => {
            console.log("did disconnect");
        });
    </script>
</body>
</html>

The problem

When I start my node server everything seems right. Executing node server.js returns listening on 3000 as supposed. When I go to index.php it never returns did connect BUT when I then exit the server node I get the did disconnect message in the browser console.

Also the server never returns anything else but listening on 3000 .

Please help me :-)

Since the recent update to v3.0.0, version 2.xx clients are not compatible so won't be able to connect.

The fix is to make sure both client and server are using the same versions, or use the server served version /socket.io/socket.io.js (which is not always possible, webpack etc)

Related issue on github: https://github.com/socketio/socket.io-client/issues/1390

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM