user2197558
user2197558

Reputation: 3

cannot get client server running using express in node.js

hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).

here is my code for the app(app.js):

var     sys         = require('sys'),
        express     = require('express'),

        app         = express('localhost');
        http    = require('http'),
        server  = http.createServer(app),

        io          = require('socket.io').listen(server);

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    res.send('Hello World');
});

app.listen(3000);

var socket = require('socket.io').listen(server);

socket.on('connection', function (client){ 
  // new client is here!
  setTimeout(function () {
        client.send('Waited two seconds!');
    }, 2000);

  client.on('message', function () {
  }) ;

  client.on('disconnect', function () {
  });
});

and here is my code for the client(client.html):

<html>
<p id="text">socket.io</p>

<script src="/socket.io/socket.io.js"></script> 


<script> 
    $(document).ready(function(){

        var socket  = new io.Socket(),
                text        = $('#text');

        socket.connect();

        socket.on('connect', function () {
            text.html('connected');
        });

        socket.on('message', function (msg) {
            text.html(msg);
        });

        socket.on('disconnect', function () {
            text.html('disconnected');
        });

    });
</script> 

i got most of the code from: NodeJS + socket.io: simple Client/Server example not working

and the changed it to be compatible with express 3.x

however when i run the server and open my client using chrome it tells me that it is unable to load resource file:///socket.io/socket.io.js

i have already installed express and socket.io using npm

also i have read through atleast 20 similar posts and have not been able to find an answer

please help me. thank you

Upvotes: 0

Views: 962

Answers (2)

vaibhavmande
vaibhavmande

Reputation: 1111

socket.io.js file needs to be served from port 3000, like localhost:3000. So here is what you do change <script src="/socket.io/socket.io.js"></script> to

<script src="http://localhost:3000/socket.io/socket.io.js"></script>

Upvotes: 2

Kevin Collins
Kevin Collins

Reputation: 1461

Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.

Upvotes: 0

Related Questions