- Socket.io provides an web socket infrastructure using Node.JS.
- It can be installed using Node Package Manger(NPM) by issuing npm -g install socket.io.
- You can check my previous post to install Node in your machine.
- In this Demo, “We will crate a simple Web Socket which will write my name on the socket and the client will read it and render it on the browser”.
- The code for web socket server is present in MyNameSocketServer.js file and listed below
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('developerName', { name: 'Sandeep Kumar Patel' });
});
- The web socket can be started by issuing node MyNameSocketServer.js command in command prompt.
- The code for client ispresent in the index-client.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Socket IO Demo</title>
<style>
h2{
color:green;
display: inline-block;
}
</style>
</head>
<body>
Author Name is : <h2 id="authorName"></h2>
<script src="http://localhost:80/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:80');
socket.on('developerName', function (data) {
var author = data.name,
element = document.getElementById("authorName");
element.innerHTML = author;
});
</script>
</body>
</html>
- The out put will render in the browser as below screenshot.
- The firebug inspection of the UI is below.You can see the socket.io javascript file is get downloded by the browser using socket server.