
In this web guide, you will be guide to create a web socket connection to server using Socket.io and HTML. Before starting, you must know some details about your server like it support web socket connection or not. These types of connection are basically used for high end applications like for chat application, virtual mining etc. In this guide, I am using socket.io for creating server then connecting to server using web socket connection. If you want to create server using Socket.io then go visit here.
Steps to Create Web Socket Connection to Server
For connecting to server we do not need any local server because we are using HTML file instead of PHP file. Before starting you must download socket.io library or you can use socket.io CDN library also as mention below
Required Libraries
Socket.io : For downloading socket.io or using socket.io cdn file visit https://cdnjs.com/libraries/socket.io.
Follow the steps to connect server using Web Socket
- First create a folder in any location in your operating system then create a file index.html inside it.
- Open that file in editor then copy and paste below code
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test Server</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> <script> //Configuring Connection var ws = io("ws://localhost:3000"); //When Connection Build ws.on('connect', function(){ alert("Connected to Server Successfully"); }); ws.on('connect_error', function(){ alert("Could not connect to server."); }); </script> </body> </html>
- Save your file then run it in your browser. You will see a alert showing Connected to Server Successfully as shown below then click OK to close it
About Code
In above code, you can see basic html tags in which we include socket.io library in script tags then created some functions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
After including library , you can see that some library functions are called as shown below
<script> //Configuring Connection var ws = io("ws://localhost:3000"); //When Connection Build ws.on('connect', function(){ alert("Connected to Server Successfully"); }); ws.on('connect_error', function(){ alert("Could not connect to server."); }); </script>
In above code, we declare a variable with name “ws” then we call “io” class of socket library and passes server address “ws://localhost:3000”. Remember server address varies according to server configuration because I am using localserver for creating server. After configuring io class, we check for connection to server is connected as shown above. If connection is established successfully then you will be alerted with message “Connected to Server Successfully”. Below that we declare another function to check for connection errors. If connection not established then you will be alerted with message “Could not connect to server”