0

It is simple chat app using node.js and socket.io. This app work fine in my local computer but do not work when I upload it to the server: Please look at my code on remote server and the problem.

Here is the code snippet of client:

<script type="application/javascript">
    var socket = io.connect();

    eventHandler(socket);

    function eventHandler(socket) { 
        socket.on('connect', function(){
            socket.emit('adduser', prompt("What's your name?"));
        });
        socket.on('error', function () {
            console.log("Connection error"); //It works after a few second with error
        });
    }

    $(document).ready(function(){
       .....
    });
</script>
Rejaul
  • 831
  • 1
  • 12
  • 35

3 Answers3

0

It looks like on the remote server Socket.IO 0.9.16 is installed (which is not up-to-date). If you're writing code according to new documentation this might be a reason why it doesn't work as you expected.

Try to upgrade Socket.IO to 1.0

Oleg
  • 22,300
  • 9
  • 68
  • 84
0

This change worked for me: you wrote this method:

var socket = io.connect();

Thanks to another help page, I switched this method to this:

var socket = io.connect('http://localhost:8080');

You can replace "localhost" with whatever ip address you use to access your server.

Also, just in case - if you haven't, it would be useful to include a connection notification on your server in the app.js file. mine looks like the following:

var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");

var server = http.createServer(function(req, res) {
 res.writeHead(200, { "Content-type": "text/html"});
 res.end(fs.readFileSync(__dirname + "/index.php"));
}).listen(8080, function() {
 console.log("Listening at http://localhost:8080");
});

socketio.listen(server).on("connection", function(socket) {
 console.log("CONNECTED");
 socket.on("message", function(msg) {
  console.log("Message received: ", msg);
  socket.broadcast.emit("message", msg);
 });
});

You can also see the help page I linked to in case they have something that more closely relates to your issue.

Community
  • 1
  • 1
-1

Your page seems to be working for me. Make sure your page is fully loaded before executing your script. This is done by using window.onload like this:

<script>
    window.onload = function() {
        //Your code here
    }
</script>
Bubbad
  • 191
  • 1
  • 1
  • 10