shadryck
shadryck

Reputation: 301

socket.io client to server confusion

I'm trying to make a simple IRC to get to understand how things work. I've set up a local node server and another workspace to connect to localhost, they talk just fine. However when I push the local server to Openshift and try to connect to it with the client with;

var socket = io.connect("http://irc-abc.rhcloud.com:3000");

It's not connecting.
What am I doing wrong here and or how can I make this work?
NOTE: I'm new to websockets and I'm trying to understand them, I'm probably missing the big picture. Yes I did find a lot of similar questions on stackoverflow however it did not help me, as I said I'm fairly new with websockets and have some trouble understanding it.

server

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;

// TO-DO verify creds against db
var credentials = {
    'username' : ''
};

io.on('connection', function(socket){
    // verify if client has username
    socket.on('login', function(credentials){
        if(credentials.username) {
            this.username = credentials.username;
            console.log( this.username  + ' connected');
            io.emit('notice', this.username  + ' connected');
        }

        else {
            console.log( 'USER GOT DENIED' );
            socket.disconnect();
        }

        // when message received
        socket.on('chat message', function (msg) {
            var message = this.username + ': ' + msg;
            io.emit('chat message', message);
        });
    });

    // when user disconnects
    socket.on('disconnect', function(){
        console.log( this.username + ' disconnected');
    });
});

http.listen(port, ip);

console.log('listening on ' + ip + ':' + port);


Client

var socket = io.connect("irc-abc.rhcloud.com:3000");
var username = '<?php if(isset($_SESSION['username'])) echo $_SESSION['username'];
else echo 'guest'; ?>';

var credentials = {
    'username' : username
};

socket.emit('login', credentials);

$('form').submit(function() {
    if ($('#m').val()) {
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
    }
    window.scrollTo(0,document.body.scrollHeight);
    return false;
});

socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
    window.scrollTo(0,document.body.scrollHeight);
});

socket.on('notice', function(notice){
    $('#messages').append($('<li>').text(notice));
    window.scrollTo(0,document.body.scrollHeight);
});

Upvotes: 0

Views: 142

Answers (1)

ajacian81
ajacian81

Reputation: 7569

The first thing I'd do is check if port 3000 is firewalled. Some (most) hosts firewall all ports that are not normally used (80, 443, etc). If you can't get them to change the firewall right away, test with port 80.

Upvotes: 1

Related Questions