Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Connecting client to server using Socket.io

Connecting client to server using Socket.io

Problem

I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.

I'm trying to get a simple HTML page on a webserver connect to a different Server running node.js with websocket.io.

My code looks like this:

Client

Serverside

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

// 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('

Hello Socket Lover!

'); }); server.listen(port); // Create a Socket.IO instance, passing it our server var socket = io.listen(server); // Add a connect listener socket.on('connection', function(client){ console.log('Connection to client established'); // 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'); }); }); console.log('Server running at http://127.0.0.1:' + port + '/');

Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.

But when I run it, nothing happens and the Chrome console returns:

Failed to load resource            http://undefined/socket.io/1/?t=1333119551736
Failed to load resource            http://undefined/socket.io/1/?t=1333119551735

I've been at this all day. Any help?

Problem courtesy of: shmow

Solution

Have you tried loading the socket.io script not from a relative URL?

You're using:

And:

socket.connect('http://127.0.0.1:8080');

You should try:

And:

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

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Solution courtesy of: Lior Cohen

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Connecting client to server using Socket.io

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×