简体   繁体   中英

Socket connection is not established on AWS EC2

I have deployed my code with docker image and here is the code for the socket connection.

I got SUCCESSFUL connection in the local system but when I deploy the same code on EC2 it gives me the following error: 在此处输入图片说明

I'm using express server.

Server:

var serverIO = require('http').Server(app);
var io = require('socket.io')(serverIO);
io.on('connection', function(client) {
    console.log('Client connected...', client.id);
})

var server = serverIO.listen(config.app.port, function(){
    console.log('server running on port:', config.app.port)
})

Client:

<!doctype html>
<html lang="en">
    <head>

    </head>
    <body>
        <h1>Hello World!</h1>
        <div id="future"></div>
        <form id="form" id="chat_form">
            <input id="chat_input" type="text">
            <input type="submit" value="Send">
        </form>
         <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
    </body>
</html>

<script>
 // var socket = io.connect('http://127.0.0.1:8000'); //here I got connection 
 var socket = io.connect('https://liveURL:8000'); //here I got error
    socket.on('connect', function(data) {
        socket.emit('join', {email: "user1@example.com"});
    });

  socket.on('broad', function(data) {
        console.log(data)
         $('#future').append(data+ "<br/>");
   });

  socket.on("new_msg", function(data) {
    console.log("here")
    alert(data.msg);
   })

 $('form').submit(function(e){
     e.preventDefault();
     var message = $('#chat_input').val();
     socket.emit('messages', {email: "user1@example.com"});
 });
</script>

You need to set the connection secure flag to true.

 var socket = io.connect('https://liveURL:8000',{secure: true}); //here I got error
    socket.on('connect', function(data) {
        socket.emit('join', {email: "user1@example.com"});
    });

You can check the offical documentation.

{
  headers: /* the headers sent as part of the handshake */,
  time: /* the date of creation (as string) */,
  address: /* the ip of the client */,
  xdomain: /* whether the connection is cross-domain */,
  secure: /* whether the connection is secure */,
  issued: /* the date of creation (as unix timestamp) */,
  url: /* the request URL string */,
  query: /* the query object */
}

Or if you are using express on the server side then you can look here and here

Updated:

I saw that there is no SSL Configuration on your server-side so https will not work.

Try with http instead

io.connect('http://liveserver:8000')

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