Home
»
Posts filed under AngularJS
What is Websocket. Use of Websocket. Client server example using Websockets, AngularJS and Java.
in
AngularJS,
Interviews,
Miscellaneous
- on 20:42:00
- No comments
What is Websocket? Use of Websocket? Client server program using Websockets, AngularJS and Java.
In this post, we will see what is websocket, use of websocket, websocket in java, websocket client server example using Websockets, AngularJS and Java.
Websocket is bi-directional communication protocol over web that helps client to server and server to client communication on single TCP connection and on same port.
What is the use of Websocket and how it is helpful?
How things works before Websocket ?
For communication on web, HTTP is the standard protocol that is used.
HTTP is stateless protocol. It means,
2. Connection established
3. Client sends a request.
4. Server gives response.
5. Connection closed Now client and server are independent and unaware of each other.
If client want to communicate again then it has to again go with above steps,
Also, request is always initiated by client and server can't initiate communication.
So, if Server has to say something to the client then how to achieve that?
First of all, why server want to communicate with the client, Lets see below example,
to Ahmedabad.
2. Server responded to Jayesh "Price is 5000 INR."
3. Jayesh is thinking whether to book a flight at 5000 INR and then finally after 5 minutes,
he made a mind to book it.
4. Now after filling long form of passenger list and other flight information,
when Jayesh pressed the "Book" button, he found that now Flight price is 6000 INR,
how this happen??????????
5. Jayesh is frustrated and thinking why server not notified him before filling the long form
on passenger list.
Ideally, Server should notify Jayesh that flight price is changed, please refresh the page.
But how the server will know that to which all clients he need to inform and top of all, Server doesn't know any information on client.
This is possible only if server is capable of identifying client that, "who all client are connected to server and notify them on updates".
As communication happens over HTTP, Before Websocket, Server notify to the client using below techniques,
1. Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server at
regular intervals (say 1 seconds).
3. The server checks for updates and responds back, just like normal HTTP response.
In Polling, client continuously polls server at
regular intervals, asking is there any updates for client?
Disadvantage: if there is no updates, then unnecessarily client sends request to server and it hits server performance.
2. Long Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server.
3. Now if server does not has any updates, then server does not immediately responds telling
"no update" instead waits until there's new information available.
When there's update available, the server responds with the updated information that help
client on information say price has changed.
4. The client receives updated price information and immediately sends another request
to the server, re-starting the process.
Disadvantage: Server like Tomcat would spawned thread to handle for each request, that reserve resources, till its done. So the traffic is smaller, but eats resources fast (also block resources).
Websocket overcome issues present in Polling and Long Polling.
One limitation with Websocket is that it is only supported with HTML 5 compliant browsers.
Lets see a sample application on updating total count of connected clients using WebSockets, AngularJS and Java.
Client Side HTML and Javascript
index.html<!DOCTYPE html>
<html>
<head>
<title>Websocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="app.js"></script>
</head>
<body data-ng-app="websocketDemoApp" style="margin:0px;">
<div data-ng-controller="appController">
<label style="font-size: 20px; font-weight: bold;">Messages from Websocket Communication : </label>
<pre>{{ websocketMessage }}</pre><br>
<label style="font-size: 20px; font-weight: bold;">Connected Clients : </label>
<label style="font-size: 40px; font-weight: bold;">{{ numberOfUsersConnected }}</label>
</div>
</body>
</html>
app.js
'use strict';
var module = angular.module('websocketDemoApp', [ ]);
angular.module('websocketDemoApp').controller("appController", ['$scope', function($scope) {
$scope.websocketMessage = "";
$scope.getURLWithOutProtocalFromCurrentContext = function() {
var hostName = window.location.host;
var currentPath = window.location.pathname;
return hostName + currentPath;
};
var urlWithOutProtocol = $scope.getURLWithOutProtocalFromCurrentContext();
var wsUri = "ws://" + urlWithOutProtocol +"endpoint";
var websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
console.log("connection established");
$scope.$apply(function(){
$scope.websocketMessage = $scope.websocketMessage + "Connection to Websocket has established." + "\n";
});
};
websocket.onmessage = function(evt) {
console.log("message received: "+evt.data);
var jsonResponse = JSON.parse(evt.data);
$scope.$apply(function(){
if(jsonResponse.count!=null || !angular.isUndefined(jsonResponse.count))
$scope.numberOfUsersConnected = jsonResponse.count;
if(jsonResponse.message!=null || !angular.isUndefined(jsonResponse.message))
$scope.websocketMessage = $scope.websocketMessage + "Data Received: " +jsonResponse.message + "\n";
});
};
websocket.onerror = function(evt) {
console.log('websocket error: ' + jsonResponse);
$scope.websocketMessage = $scope.websocketMessage + "There is some error while establishing connection to web socket." + "\n";
};
websocket.onclose = function(){
$scope.websocketMessage = $scope.websocketMessage + "Web Socket connection is closed now..." + "\n";
};
}]);
Server Side Java Code
ServerPush.java
package javabypatel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/endpoint")
public class ServerPush {
private static Map<Object, Session> mapConnections = new HashMap<Object, Session>();
public ServerPush() {
//Starting notifier to push data to client at 1 minute interval
new NotifierExample();
}
//This method is called when websocket connection is established or open.
@OnOpen
public void start(Session session) {
mapConnections.put(session.getId(), session);
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//This method is called when websocket connection is closed or when browser tab is closed.
@OnClose
public void end(Session session, CloseReason reason) {
mapConnections.remove(session.getId());
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//For sending data to single connected client for one to one communication between client and server.
public static void broadcast(String key, String message) {
Session session = mapConnections.get(key);
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
//For sending data to all the connected clients
public static void broadcastToAll(String message) {
for(Session session : mapConnections.values()){
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
}
}
NotifierExample.java
package javabypatel;
import java.util.Timer;
import java.util.TimerTask;
public class NotifierExample extends TimerTask{
//After every 60 seconds, server will push the data to all connected clients.
public NotifierExample() {
Timer timer = new Timer();
timer.schedule(this, 5000, 60000);
}
@Override
public void run() {
String json = "{ \"message\" : \"Database table is updated, Please refresh to get updated records.\"}";
ServerPush.broadcastToAll(json);
}
}
Note: ServerPush.java use classes from websocket jar, So make sure you have websocker-api.jar present in tomcat lib folder, if not then download using below dependency,
javax.websocket javax.websocket-api 1.0
After setup, Run the application in Tomcat.
- Open browser and try to access application "https://localhost:8080/AppName"
- Now, open firefox browser and try to access application "https://localhost:8080/AppName"
the server pushes the total connected client count information on browser as well without explicit request from client
Output:
You may also like to see
Number Range Spinner in Angular JS
Using JQuery Datatable in AngularJS application.
Download binary file AngularJS + REST service
Configure Angular2 + Webpack + Maven Sample
Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space.
Count number of Bits to be flipped to convert A to B
Count number of Set Bits in Integer.
Check if number is Power of Two.
Find all subsets of a set (Power Set).
Skyline Problem in Java.
Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted
Count trailing zeros in factorial of a number
When to use SOAP over REST Web Service. Is REST better than SOAP?
Tower Of Hanoi Program in Java.
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
What is Websocket? Use of Websocket? Sample program using Websockets, AngularJS and Java
in
AngularJS,
Interviews,
Miscellaneous
- on 20:54:00
- No comments
What is Websocket?
In this post, we will see what is websocket? use of websocket? Hello world program using Websockets, AngularJS and Java. Websocket is bi-directional communication protocol over web that helps client to server and server to client communication on single TCP connection and on same port.
What is the use of Websocket and how it is helpful?
How things works before Websocket ?
For communication on web, HTTP is the standard protocol that is used.
HTTP is stateless protocol. It means,
2. Connection established
3. Client sends a request.
4. Server gives response.
5. Connection closed Now client and server are independent and unaware of each other.
If client want to communicate again then it has to again go with above steps,
Also, request is always initiated by client and server can't initiate communication.
So, if Server has to say something to the client then how to achieve that?
First of all, why server want to communicate with the client, Lets see below example,
to Ahmedabad.
2. Server responded to Jayesh "Price is 5000 INR."
3. Jayesh is thinking whether to book a flight at 5000 INR and then finally after 5 minutes,
he made a mind to book it.
4. Now after filling long form of passenger list and other flight information,
when Jayesh pressed the "Book" button, he found that now Flight price is 6000 INR,
how this happen??????????
5. Jayesh is frustrated and thinking why server not notified him before filling the long form
on passenger list.
Ideally, Server should notify Jayesh that flight price is changed, please refresh the page.
But how the server will know that to which all clients he need to inform and top of all, Server doesn't know any information on client.
This is possible only if server is capable of identifying client that, "who all client are connected to server and notify them on updates".
As communication happens over HTTP, Before Websocket, Server notify to the client using below techniques,
1. Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server at
regular intervals (say 1 seconds).
3. The server checks for updates and responds back, just like normal HTTP response.
In Polling, client continuously polls server at
regular intervals, asking is there any updates for client?
Disadvantage: if there is no updates, then unnecessarily client sends request to server and it hits server performance.
2. Long Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server.
3. Now if server does not has any updates, then server does not immediately responds telling
"no update" instead waits until there's new information available.
When there's update available, the server responds with the updated information that help
client on information say price has changed.
4. The client receives updated price information and immediately sends another request
to the server, re-starting the process.
Disadvantage: Server like Tomcat would spawned thread to handle for each request, that reserve resources, till its done. So the traffic is smaller, but eats resources fast (also block resources).
Websocket overcome issues present in Polling and Long Polling.
One limitation with Websocket is that it is only supported with HTML 5 compliant browsers.
Lets see a sample application on updating total count of connected clients using WebSockets, AngularJS and Java.
Client Side HTML and Javascript
index.html<!DOCTYPE html>
<html>
<head>
<title>Websocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="app.js"></script>
</head>
<body data-ng-app="websocketDemoApp" style="margin:0px;">
<div data-ng-controller="appController">
<label style="font-size: 20px; font-weight: bold;">Messages from Websocket Communication : </label>
<pre>{{ websocketMessage }}</pre><br>
<label style="font-size: 20px; font-weight: bold;">Connected Clients : </label>
<label style="font-size: 40px; font-weight: bold;">{{ numberOfUsersConnected }}</label>
</div>
</body>
</html>
app.js
'use strict';
var module = angular.module('websocketDemoApp', [ ]);
angular.module('websocketDemoApp').controller("appController", ['$scope', function($scope) {
$scope.websocketMessage = "";
$scope.getURLWithOutProtocalFromCurrentContext = function() {
var hostName = window.location.host;
var currentPath = window.location.pathname;
return hostName + currentPath;
};
var urlWithOutProtocol = $scope.getURLWithOutProtocalFromCurrentContext();
var wsUri = "ws://" + urlWithOutProtocol +"endpoint";
var websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
console.log("connection established");
$scope.$apply(function(){
$scope.websocketMessage = $scope.websocketMessage + "Connection to Websocket has established." + "\n";
});
};
websocket.onmessage = function(evt) {
console.log("message received: "+evt.data);
var jsonResponse = JSON.parse(evt.data);
$scope.$apply(function(){
if(jsonResponse.count!=null || !angular.isUndefined(jsonResponse.count))
$scope.numberOfUsersConnected = jsonResponse.count;
if(jsonResponse.message!=null || !angular.isUndefined(jsonResponse.message))
$scope.websocketMessage = $scope.websocketMessage + "Data Received: " +jsonResponse.message + "\n";
});
};
websocket.onerror = function(evt) {
console.log('websocket error: ' + jsonResponse);
$scope.websocketMessage = $scope.websocketMessage + "There is some error while establishing connection to web socket." + "\n";
};
websocket.onclose = function(){
$scope.websocketMessage = $scope.websocketMessage + "Web Socket connection is closed now..." + "\n";
};
}]);
Server Side Java Code
ServerPush.java
package javabypatel;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/endpoint")
public class ServerPush {
private static Map<Object, Session> mapConnections = new HashMap<Object, Session>();
public ServerPush() {
//Starting notifier to push data to client at 1 minute interval
new NotifierExample();
}
//This method is called when websocket connection is established or open.
@OnOpen
public void start(Session session) {
mapConnections.put(session.getId(), session);
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//This method is called when websocket connection is closed or when browser tab is closed.
@OnClose
public void end(Session session, CloseReason reason) {
mapConnections.remove(session.getId());
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//For sending data to single connected client for one to one communication between client and server.
public static void broadcast(String key, String message) {
Session session = mapConnections.get(key);
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
//For sending data to all the connected clients
public static void broadcastToAll(String message) {
for(Session session : mapConnections.values()){
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
}
}
NotifierExample.java
package javabypatel;
import java.util.Timer;
import java.util.TimerTask;
public class NotifierExample extends TimerTask{
//After every 60 seconds, server will push the data to all connected clients.
public NotifierExample() {
Timer timer = new Timer();
timer.schedule(this, 5000, 60000);
}
@Override
public void run() {
String json = "{ \"message\" : \"Database table is updated, Please refresh to get updated records.\"}";
ServerPush.broadcastToAll(json);
}
}
Note: ServerPush.java use classes from websocket jar, So make sure you have websocker-api.jar present in tomcat lib folder, if not then download using below dependency,
javax.websocket javax.websocket-api 1.0
After setup, Run the application in Tomcat.
- Open browser and try to access application "http://localhost:8080/AppName"
- Now, open firefox browser and try to access application "http://localhost:8080/AppName"
the server pushes the total connected client count information on browser as well without explicit request from client
Output:
You may also like to see
Number Range Spinner in Angular JS
Using JQuery Datatable in AngularJS application.
Download binary file AngularJS + REST service
Configure Angular2 + Webpack + Maven Sample
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
Configure Angular2 + Webpack + Maven Sample
in
AngularJS,
Miscellaneous
- on 12:26:00
- No comments
Configure Angular2 + Webpack in Maven build.
Build application using Angular2 with Typescript, Webpack as Module Bundler and Maven as build environment. We will also use Angular 2 with bootstrap.js and jquery.js library
What is Webpack
Webpack is a powerful module bundler. A bundle is common JavaScript file that combine html data, css data, javascript data etc in common file together and should be served to the client in a response to a single file request.
Let's start building application using Angular2 and Typescript.
We will use Bootstrap + Jquery with Angular2 and Typescript in our sample application.
Download application from github: Angular2WebPackMaven
How output will look like:
Angular2 Typescript files:
1. index.html
Application single page application html file which contain placeholder to display
components.
2. main.ts
Application entry point file, this is the place where we have imported all application
dependencies.
index.html is simply a template, Required javascript's, css etc are mentioned in main.ts
Also, which module to load in placeholder is also present in main.ts
3. app folder
It contains application typescript files (modules, component, services, routes, models etc)
4. resources folder
It contains application external resources like javascript, css etc that need to be bundled.
5. package.json
A package.json file contains meta data about our app.
It includes list of dependencies to install for development and production environment.
6. webpack.config.js
Webpack configuration file
Download code from link : Angular2WebPackMaven
Steps to run the application:
1. After downloading the application, run "mvn install" in home directory as shown below,
(It will take some time to download all development dependencies)
2. For running the application, go to browser and hit
"http://ip:port/Angular2WebPackMaven/angular2-webpack-maven"
You may also like to see
Number Range Spinner in Angular JS
Download binary file AngularJS + REST service
What is Websocket? How Websocket works? Program on updating total count of connected Clients.
Using JQuery Datatable with AngularJS
Top 25 Multithreading Interview Questions In Java
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
Download binary file AngularJS + REST service
in
AngularJS,
Miscellaneous,
Web Service
- on 11:35:00
- No comments
Download binary file using AngularJS + REST service
Many a times we need to download file via POST request, because the request contains extra parameters to pass and GET request is not suitable.
Example demonstrates downloading binary file using Javascript and REST service
Once I have faced requirement of downloading binary zip file using AngularJS + REST service and thought of sharing the code, It may help to someone facing similar requirement.
Many a times we need to download file via POST request, because the request contains extra parameters to pass and GET request is not suitable.
![]() |
| Download file from server example in AngularJS |
Lets see example of downloading ZIP file via POST request.
For downloading file in Angular2 look at this post: Download file in Angular2
For downloading file in Angular2 look at this post: Download file in Angular2
Once I have faced requirement of downloading binary zip file using AngularJS + REST service and thought of sharing the code, It may help to someone facing similar requirement.
What is Websocket? How Websocket works? Program on updating total count of connected Clients.
What is Websocket?
Websocket is bi-directional communication protocol over web that helps client to server and server to client communication on single TCP connection and on same port.
What is the use of Websocket and how it is helpful?
How things works before Websocket ?
For communication on web, HTTP is the standard protocol that is used.
HTTP is stateless protocol. It means,
2. Connection established
3. Client sends a request.
4. Server gives response.
5. Connection closed
Now client and server are independent and unaware of each other.
If client want to communicate again then it has to again go with above steps,
Also, request is always initiated by client and server can't initiate communication.
So, if Server has to say something to the client then how to achieve that?
First of all, why server want to communicate with the client, Lets see below example,
to Ahmedabad.
2. Server responded to Jayesh "Price is 5000 INR."
3. Jayesh is thinking whether to book a flight at 5000 INR and then finally after 5 minutes,
he made a mind to book it.
4. Now after filling long form of passenger list and other flight information,
when Jayesh pressed the "Book" button, he found that now Flight price is 6000 INR,
how this happen??????????
5. Jayesh is frustrated and thinking why server not notified him before filling the long form
on passenger list.
Ideally, Server should notify Jayesh that flight price is changed, please refresh the page.
But how the server will know that to which all clients he need to inform and top of all, Server doesn't know any information on client.
This is possible only if server is capable of identifying client that, "who all client are connected to server and notify them on updates".
As communication happens over HTTP, Before Websocket, Server notify to the client using below techniques,
1. Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server at
regular intervals (say 1 seconds).
3. The server checks for updates and responds back, just like normal HTTP response.
In Polling, client continuously polls server at
regular intervals, asking is there any updates for client?
Disadvantage: if there is no updates, then unnecessarily client sends request to server and it hits server performance.
2. Long Polling
In this technique,
2. The requested webpage executes JavaScript which requests for updates from the server.
3. Now if server does not has any updates, then server does not immediately responds telling
"no update" instead waits until there's new information available.
When there's update available, the server responds with the updated information that help
client on information say price has changed.
4. The client receives updated price information and immediately sends another request
to the server, re-starting the process.
Disadvantage: Server like Tomcat would spawned thread to handle for each request, that reserve resources, till its done. So the traffic is smaller, but eats resources fast (also block resources).
Websocket overcome issues present in Polling and Long Polling.
One limitation with Websocket is that it is only supported with HTML 5 compliant browsers.
Lets see a sample application on updating total count of connected clients using WebSockets, AngularJS and Java.
Client Side HTML and Javascript
index.html<!DOCTYPE html>
<html>
<head>
<title>Websocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="app.js"></script>
</head>
<body data-ng-app="websocketDemoApp" style="margin:0px;">
<div data-ng-controller="appController">
<label style="font-size: 20px; font-weight: bold;">Messages from Websocket Communication : </label>
<pre>{{ websocketMessage }}</pre><br>
<label style="font-size: 20px; font-weight: bold;">Connected Clients : </label>
<label style="font-size: 40px; font-weight: bold;">{{ numberOfUsersConnected }}</label>
</div>
</body>
</html>
app.js
'use strict';
var module = angular.module('websocketDemoApp', [ ]);
angular.module('websocketDemoApp').controller("appController", ['$scope', function($scope) {
$scope.websocketMessage = "";
$scope.getURLWithOutProtocalFromCurrentContext = function() {
var hostName = window.location.host;
var currentPath = window.location.pathname;
return hostName + currentPath;
};
var urlWithOutProtocol = $scope.getURLWithOutProtocalFromCurrentContext();
var wsUri = "ws://" + urlWithOutProtocol +"endpoint";
var websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
console.log("connection established");
$scope.$apply(function(){
$scope.websocketMessage = $scope.websocketMessage + "Connection to Websocket has established." + "\n";
});
};
websocket.onmessage = function(evt) {
console.log("message received: "+evt.data);
var jsonResponse = JSON.parse(evt.data);
$scope.$apply(function(){
if(jsonResponse.count!=null || !angular.isUndefined(jsonResponse.count))
$scope.numberOfUsersConnected = jsonResponse.count;
if(jsonResponse.message!=null || !angular.isUndefined(jsonResponse.message))
$scope.websocketMessage = $scope.websocketMessage + "Data Received: " +jsonResponse.message + "\n";
});
};
websocket.onerror = function(evt) {
console.log('websocket error: ' + jsonResponse);
$scope.websocketMessage = $scope.websocketMessage + "There is some error while establishing connection to web socket." + "\n";
};
websocket.onclose = function(){
$scope.websocketMessage = $scope.websocketMessage + "Web Socket connection is closed now..." + "\n";
};
}]);
Server Side Java Code
ServerPush.javapackage com.websocket.test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/endpoint")
public class ServerPush {
private static Map<Object, Session> mapConnections = new HashMap<Object, Session>();
public ServerPush() {
//Starting notifier to push data to client at 1 minute interval
new NotifierExample();
}
//This method is called when websocket connection is established or open.
@OnOpen
public void start(Session session) {
mapConnections.put(session.getId(), session);
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//This method is called when websocket connection is closed or when browser tab is closed.
@OnClose
public void end(Session session, CloseReason reason) {
mapConnections.remove(session.getId());
String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
broadcastToAll(json);
}
//For sending data to single connected client for one to one communication between client and server.
public static void broadcast(String key, String message) {
Session session = mapConnections.get(key);
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
//For sending data to all the connected clients
public static void broadcastToAll(String message) {
for(Session session : mapConnections.values()){
if(session!=null){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
}
}
NotifierExample.javapackage com.websocket.test;
import java.util.Timer;
import java.util.TimerTask;
public class NotifierExample extends TimerTask{
//After every 60 seconds, server will push the data to all connected clients.
public NotifierExample() {
Timer timer = new Timer();
timer.schedule(this, 5000, 60000);
}
@Override
public void run() {
String json = "{ \"message\" : \"Database table is updated, Please refresh to get updated records.\"}";
ServerPush.broadcastToAll(json);
}
}
Note: ServerPush.java use classes from websocket jar, So make sure you have websocker-api.jar present in tomcat lib folder, if not then download using below dependency,
javax.websocket javax.websocket-api 1.0
After setup, Run the application in Tomcat.
- Open browser and try to access application "http://localhost:8080/AppName"
- Now, open firefox browser and try to access application "http://localhost:8080/AppName"
the server pushes the total connected client count information on browser as well without explicit request from client
Output:
Number Range Spinner in Angular JS
Using JQuery Datatable in AngularJS application.
Download binary file AngularJS + REST service
Configure Angular2 + Webpack + Maven Sample
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
Using JQuery Datatable with AngularJS
in
AngularJS
- on 11:23:00
- No comments
Datatables - AngularJS
| Using JQuery Datatable with AngularJS |
Datatables
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool for rendering data in tables with features like,
- Searching record/row in table.
- Sorting columns.
- Pagination etc.














