Websockets in frontend by using JavaScript...
The main thing that we have to know is that we have 2 types of WebSocket URLs
1: ws: It will be used from the backend which will work fine with any process.
2: wss: It's the type by which most frontend WebSockets work.
So, We are also using wss: URL, as working from the javascript frontend.
firstly we need to check whether our web browser supports WebSockets or not by using the below code
if ("WebSocket" in window) {
// Code continues here
}else{
alert("WebSocket NOT supported by your Browser!");
}
If the web browser supports WebSockets then, the next step will be
Creating a connection between WebSockets URL and our browser, By using the below code.
ws = new WebSocket('wss://3333.port.apps.webgrid.in');
When we call WebSocket for connection on connect it will send some data and by that, we will stay connected for any action with WebSocket, we will get on-connect as below.
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
};
Then we have 2 main actions which will help us to work on WebSocket.
1: on message received from WS
2: send a message to WS
1:on message received from WS:
Basically, we have to get a response when we receive a message from WS to get the receiving messages below code will be used.
ws.onmessage = function(evt) {
// Code or any action to take on message from evt
}
2: send a message to WS
To send a message to WS we simply have to convert our data into JSON format and use the below code.
ws.send(json_data);
Then later we have to disconnect the connection by using below
ws.onclose = function() {
//any action if connection disconnect
}
The Simple Example is below:
if ("WebSocket" in window) {
ws = new WebSocket('wss://3333.port.apps.webgrid.in');
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send"); // sending data to server.
};
ws.onmessage = function(evt) {
// Code or any action to take on message from evt
}
ws.send(json_data); // to send any data to server
ws.onclose = function() {
//any action if connection disconnect
}
}else{
alert("WebSocket NOT supported by your Browser!");
}
Thank you, Have a good day...
