meltuhamy
meltuhamy

Reputation: 3493

Can't get up and running with socket.io

I'm running on Windows and using WAMP for a localhost server. I've searched alot for tutorials, tried many things etc. but still nothing works..

Current Setup

So write now, in my www/ directory, I created a folder called socketiodemo.

In it, I did npm install socket.io as well as installing a few other node packages:

I installed all the above packages even though I don't actually need them. I just installed them since a lot of tutorials needed them but I'd rather not use them and just get to pure socket.io with javascript.

So, here's a snapshot of my directory under www:

One of the most stripped down tutorials I found gave me this app.js code, which is the server side:

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

    // Send HTML headers and message
    res.writeHead(200,{ 'Content-Type': 'text/html' }); 
    res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.sockets.on('connection', function(client){ 

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

    // Success!  Now listen to messages to be received
    client.on('message',function(event){ 
        console.log('Received message from client!',event);
    });
    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});

And the following index.html for the client code:

<!DOCTYPE html>
<html>
<head>
    <style>
        * { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
        body { padding:20px; }
        #message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
        #message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
        code { font-family:courier; background:#eee; padding:2px 4px; }
    </style>
    <script src="http://cdn.socket.io/stable/socket.io.js"></script>
    <script>

        // Create SocketIO instance
        var socket = new io.Socket('localhost',{
            port: 8080
        });
        socket.connect(); 

        // Add a connect listener
        socket.on('connect',function() {
            log('<span style="color:green;">Client has connected to the server!</span>');
        });
        // Add a connect listener
        socket.on('message',function(data) {
            log('Received a message from the server:  ' + data);
        });
        // Add a disconnect listener
        socket.on('disconnect',function() {
            log('<span style="color:red;">The client has disconnected!</span>');
        });

        // Sends a message to the server via sockets
        function sendMessageToServer(message) {
            socket.send(message);
            log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
        }

        // Outputs to console and list
        function log(message) {
            var li = document.createElement('li');
            li.innerHTML = message;
            document.getElementById('message-list').appendChild(li);
        }

    </script>
</head>
<body>

    <p>Messages will appear below (and in the console).</p><br />
    <ul id="message-list"></ul>
    <ul style="margin:20px 0 0 20px;">
        <li>Type <code>socket.disconnect()</code> to disconnect</li>
        <li>Type <code>socket.connect()</code> to reconnect</li>
        <li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
    </ul>

</body>
</html>

The client code is designed to work by dynamically calling sendMessageToServer('Your Message') in chrome's inspector.


Current output

So, time to run the server. WAMP is online, and going to www/socketiodemo and doing

node app.js

Gives me the output:

info - socket.io started

Now, going to localhost/socketiodemo, the following logs are shown repeatedly:

XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1338578840544. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest cannot load http://localhost:8080/socket.io/xhr-polling//1338578850545. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

And now the server (node app.js) starts displaying the following messages:

  info  - socket.io started
  warn  - unknown transport: "undefined"
  info  - unhandled socket.io url
  warn  - unknown transport: "undefined"
  info  - unhandled socket.io url
  warn  - unknown transport: "undefined"

Also, in the client, doing sendMessageToServer('Hello'); simply appends to the ul: Sending "hello" to the server! but doesn't actually do anything to the server. The server just conterminously dumps the infos and warns above. The client is also conterminously doing the XMLHttpRequest errors shown above.

Could you identify where the problem is? I've actually tried so many tutorials and stuff and this is the closest I've got to getting something working.

If anyone also wants to suggest a tutorial that they know would work, please do so.

Upvotes: 1

Views: 6075

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159125

Some of the Socket.IO stuff has changed over time. Furthermore, you probably want to serve your HTML and your Socket.IO JS from the same host/port. Give this a try:

Move your index.html into a public directory

So that you have the following tree:

app.js
public/
  index.html
node_modules/
  socket.io
  express
  (whatever else)

Modify app.js to serve the HTML

Change your app.js to the following JavaScript (only the first few lines change):

// Require Express module (to start server) and Socket.IO
var io = require('socket.io'), express = require('express');

var server = express.createServer();

server.use(express.static(__dirname + "/public"));

server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.sockets.on('connection', function(client){

    // Create periodical which ends a message to the client every 5 seconds
    var interval = setInterval(function() {
        client.send('This is a message from the server!  ' + new Date().getTime());
    },5000);

    // Success!  Now listen to messages to be received
    client.on('message',function(event){
        console.log('Received message from client!',event);
    });
    client.on('disconnect',function(){
        clearInterval(interval);
        console.log('Server has disconnected');
    });

});

With this code, your server will use Express to serve index.html when you visit localhost:8080

Change your Socket.IO code

In index.html, change your <script> tag to read: <script src="/socket.io/socket.io.js"></script> and then change the JavaScript to read (only the first part changes):

// Create SocketIO instance
var socket = io.connect();

// Add a connect listener
socket.on('connect',function() {
    log('<span style="color:green;">Client has connected to the server!</span>');
});
// Add a connect listener
socket.on('message',function(data) {
    log('Received a message from the server:  ' + data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
    log('<span style="color:red;">The client has disconnected!</span>');
});

// Sends a message to the server via sockets
function sendMessageToServer(message) {
    socket.send(message);
    log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}

// Outputs to console and list
function log(message) {
    var li = document.createElement('li');
    li.innerHTML = message;
    document.getElementById('message-list').appendChild(li);
}

Start your server and visit localhost:8080

Note that this skips the WAMP stack all together; Node.js is serving both Socket.IO code and also your static files. When you visit localhost:8080, you should see the messages. Note also that you should use socket.socket.disconnect() to disconnect and socket.socket.connect() to reconnect.

Source Code

The source code for a working version of this app is at https://github.com/BinaryMuse/so-10856370; remember to npm install express socket.io!

Upvotes: 4

Related Questions