Sunday, 16 April 2017

Socket.io not working on aws with nodejs

I am trying to connect to socket on aws ec2 instance. For some reason I am not able to do so . My client side code is :

var socket = io.connect('http://ec2-MY-IP.us-west-2.compute.amazonaws.com:3000');
            console.log(socket);
                    socket.on('connect', function(){
                      alert(socket.id); // 'G5p5...
                    });
   socket.on('connect_error', function(){
                console.log('Connection Failed');
            });

I Always get "Connection Failed" In browser console

I have opened the port from the security group's Inbound section and when I use :

 telnet ec2-MY-IP.us-west-2.compute.amazonaws.com 3000

It gives me output

 Trying ...
 Connected to ec2-MY-IP.us-west-2.compute.amazonaws.com.
 Escape character is '^]'.

My server Side Code goes HERE :

 const express = require('express');
 const bodyParser= require('body-parser');
 const app = express();
 var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, () => {
console.log('listening on 3000');
  });
    MongoClient.connect('mongodb://ec2-MY-IP.us-west-2.compute.amazonaws.com:27017/userlogsdemo', (err, database) => {
  if (err) return console.log(err)
 db = database;
console.log("DB CONNECTED")
io.on('connection', function (socket) {
    console.log("SOCKET CONNECTED")
    socketobj = socket
     socket.on('reloadtickets', function (data) {
    connectedusers.forEach(function(v){
            if(v.connecteduserid == data.target){ 
                setTimeout(function () {
                   io.emit('reloadticketsok',data );
                }, 100)


            }
        });
});
 // WHEN SOMEONE IS DISCONNECTED


 }); 

 })

When I RUN "node server.js" It says "DB CONNECTED" but not "SOCKET CONNECTED". Code with localhost:8080(ON my local machine not on aws) works properly. Is there Anything special required to be done on aws Ec2. Any suggestions will be appreciated . Thanks in advance



via Drawtopic Dev

No comments:

Post a Comment