[javascript] Connecting client to server using Socket.io

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

<script src="socket.io/socket.io.js"></script>
<script>
    // Create SocketIO instance, connect

    var socket = new io.Socket();

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

    // Add a connect listener
    socket.on('connect',function() {
      console.log('Client has connected to the server!');
    });
    // Add a connect listener
    socket.on('message',function(data) {
      console.log('Received a message from the server!',data);
    });
    // Add a disconnect listener
    socket.on('disconnect',function() {
      console.log('The client has disconnected!');
    });

    // Sends a message to the server via sockets
    function sendMessageToServer(message) {
      socket.send(message);
    };
</script>

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('<h1>Hello Socket Lover!</h1>');
});

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?

This question is related to javascript html node.js websocket socket.io

The answer is


You need to make sure that you add forward slash before your link to socket.io:

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

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to websocket

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED WebSockets and Apache proxy : how to configure mod_proxy_wstunnel? javax.websocket client simple example getting the reason why websockets closed with close code 1006 Websocket onerror - how to read error description? WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets? How to make cross domain request How to use Tomcat 8 in Eclipse? Setting up a websocket on Apache? Differences between TCP sockets and web sockets, one more time

Examples related to socket.io

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 WebSockets and Apache proxy : how to configure mod_proxy_wstunnel? node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON] Socket.io + Node.js Cross-Origin Request Blocked Node.js: socket.io close client connection How to send a message to a particular client with socket.io Socket.IO handling disconnect event Get connection status on Socket.io client Which websocket library to use with Node.js? Maximum concurrent Socket.IO connections