Socket Programming in JavaScript

Socket Programming in JavaScript

Sockets is a protocol that makes communication between two different processes on the same or different servers. And in now days it vastly used in real-time applications like, Instant messengers, Push Notifications, Collaboration Applications and Online Gaming.

In JavaScript we are using Socket.IO library.

What is Socket.IO?

Socket.IO is a JavaScript library that gives event-driven communication features for use in real-time applications. It has client-side browser library and a server-side Node.js library, both consists the similar syntax to enable an easily scriptable interface for developers.

The basic function of Socket.IO is to behave as an abstraction layer for existing real-time protocols. In specifically, Socket.IO can connect clients with servers over a WebSocket connection.

Socket.IO initialise a connection by using its own transport protocol negotiation method, which automatically attempts to open a WebSocket connection in the browser. If the client does not support WebSocket, a fallback is provided in the form of a long-polling connection. Either way, the Socket.IO interface remains the same. Socket.IO connections may also be multiplexed and broadcast across grouped connection channels from within the same connection.

Lets dig into expample?

So we assume you have nodejs and npm installed in your system and lets create new project.

mkdir socket-demo
cd socket-demo
npm init –y

The last command creates a package.json file in the socket-demo project folder, and Now, we will install SocketIO.

npm i socket.io

Next, we install the client library for SocketIO.

npm i socket.io-client

Building the server.

const http = require('http').createServer()
const io = require('socket.io')(http)
const port = 3000
http.listen(port, () => log(`server listening on port: ${port}`))io.on('connection', (socket) => {
    console.('Client connected')
    socket.on('message', data => {
	console.log(“Data received”, data)
    })
})io.on('disconnect', (evt) => {
    log('Client left')
})

We set up a connection event, the function callback has a socket argument. The socket registers a message event, it has a handler function that broadcast the data evt passed to it to all other sockets connected to the server when the message event is fired.

Building the Client.

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io('http://localhost:3000');
    socket.emit('message', {key:1, value:”Passed”});
  </script>
</body>
</html>

In this case our node server would remain running continuously and when we ran html client at that time socket will send data to the NodeJS server every time.