Socket.IO enables real-time bidirectional event-based communication.It works on every platform, browser or device, focusing equally on reliability and speed.there are core feature of socket.io

  1. Real-time analytics
  2. Instant messaging and chat
  3. Binary streaming
  4. Document collaboration

See Demo : https://www.youtube.com/watch?v=piuE5rbaQhU

Creating a real-time server:

To start with, create an empty directory named sockectapinodejs:

mkdir sockectapinodejs

then move inside the newly created directory:

cd sockectapinodejs

Then Run initialize the package.json by running Command: 

npm init

We also need to install Socket.io, which is the main dependency of our project, ExpressJS,Http.

npm install --save socket.io express http

Creating a real-time server: the code

Create a file named server.js inside your project’s directory. This will hold the actual server

// Import all our dependencies
var express  = require('express');
var app      = express();
var server   = require('http').Server(app);
var io       = require('socket.io')(server);
// tell express where to serve static files from
app.use(express.static(__dirname + '/public'));
server.listen(9992);
console.log('It\'s going down in 9992');
// allow CORS
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
  if (req.method == 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});
app.get('/', function(req, res) {
  //send the index.html in our public directory
  res.sendfile('index.html');
});

A result from this code : 

Working WebSocket using this now you have setup nodejs and socket.io.

//Listen for connection
io.on('connection', function(socket) {
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  }); }); 

 

Working Real-time chats web Application. :)

 

Github Link: https://github.com/Sudarshan101/sockectapinodejs

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment