Mohammed Mohammed - 1 month ago 21
Node.js Question

How to use socket.io to handle requests?

I am trying to use socket.io for handling requests between html page and http server I got Cannot POST / [HTTP/1.1 404 Not Found 1ms]
the server code:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
console.log(__dirname);
app.use(express.static(__dirname+'/public'));
app.get('/', function(req, res){
res.sendfile(__dirname+'/public/registration.html');
});

io.on('connection', function(socket){

socket.on('registration',function(msg){
console.log('user data'+ msg);
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});


html page like the following



<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.3.4.js">
var socket = io('http://localhost');
console.log(socket);
socket.emit('registration',"test");
</script>

</head>
<body>

Answer
  1. Install node,
  2. Create a folder for your app,
  3. Create package.json file:

    { "name": "socket.io-test", "version": "0.0.1", "private": true, "scripts": { "start": "node server" }, "dependencies": { "express": "~4.13.1", "socket.io": "^1.4.6" } }

  4. Run npm install,

  5. Create server.js - your original code pasted here:

    var express = require('express');
    var app = express();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    console.log(__dirname);
    app.use(express.static(__dirname+'/public'));
    app.get('/', function(req, res){
      res.sendfile(__dirname+'/public/registration.html');
    });
    io.on('connection', function(socket){
        socket.on('registration',function(msg){
        console.log('user data'+ msg);
      });
    });
    
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });
    
  6. Create the /public folder in your working directory,

  7. Create /public/registration.html file:

    <html> <head> <script src='/socket.io/socket.io.js'></script> <script> var socket = io('http://localhost:3000'); socket.on('connect', function() { socket.emit('registration',"test"); document.getElementById('socket').innerHTML='connected'; }); </script> </head> <body> <h1>Testing socket.io with nodejs</h1> <h3 id="socket"></h3> </body> </html>

  8. Start the server with node server or npm start,

  9. Go to localhost:3000 in your browser

It will work

Comments