
In this post, we demonstrate how to use websocket to implement two way communication between server and client. Typical HTTP, only client could initiate request to server. Right after server received request from client, server will send back the response to that particalar client. This is unsuitable for the applcation that need, real time update, due to client doesn't know when the event will occured at the server side. Websocket is technology that implement two way full duplex communincation between client and server. This mean that communication between client and server can happend at the real time.
- Websocket use TPC base one two peers
- Websocket use HTTP request to initiate communication and create new connection for each request/response
- Websocket communication overhead is very small
In Java EE (Wildlfy),Websocket has become part of the specification. You can refer in JSR 356: JavaTM API for WebSocket.
![]() |
Fig 0 1Web socket communication |
below we will demonstrate we create websocket end point and create client to communicate with that websocket.
Table Content
Our post is organized as following.
- Create Websocket Endpoint at server side
- Create Websocket Client at client side
- Test Websocket Communication
- Secured comminucation over Websocket
- Reference
1.Create Websocket Endpoin at Server Side
Since websocket use HTTP to initiate communication and establish connection, so we need to create web application to create websocket endpoint. We just need to simply create Dynamic Web Application in Eclipse.
|
Fig 02 Create Web Application |
|
Fig 03 Create Dynamic Web Application |
Next is to create Websocket endpoint by just simply create following java class. Luckily web socket is part of Java EE specification, so we don't need to add any library to our project.
package pro.tikkwiki.wsc;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
@ServerEndpoint(value="/hello")
public class MessageEndPoint {
private static Logger logger = Logger.getLogger(MessageEndPoint.class);
@OnOpen
public void onOpen(Session session) {
logger.debug("onOpen::" + session.getId());
String info = "Hello Client " + session.getId() + "!";
logger.debug(info);
}
@OnClose
public void onClose(Session session) {
String str = "onClose::" + session.getId();
logger.debug(str);
}
@OnMessage
public void onMessage(String message, Session session) {
String str = " Server Site Message= " + message;
logger.debug(str);
try {
session.getBasicRemote().sendText(str);
} catch (IOException e) {
logger.debug("Error occured while try to received message", e);
}
}
@OnError
public void onError(Throwable t) {
logger.debug("onError:: occured", t);
}
}
Now, we just created websocket end point for full duplex communication.Next is to create client side that will communicate with server side through the websocket.
After Create java class for
2.Create Websocket Client at client side
The client side we need to create is javascript and page as below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Websocket on Wildlfy</title>
</h:head>
<body>
<rich:panel>
<f:facet name="header">
Write your own custom rich components with built-in AJAX support
</f:facet>
<div >
<h:outputText value="Hello World Websocket." />
</div>
</rich:panel>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8080/java-ee-07-wsc/hello";
var ws = new WebSocket(wsUri);
ws.onopen = function()
{
alert("Web Socket is connected!!");
var i=0;
while(i!=5){
ws.send("Hellllllloxxxxxxxxxxxxx - "+i);
i++;
}
};
ws.onmessage = function (evt)
{
var msg = evt.data;
console.log("Message received:" + msg);
};
ws.onclose = function()
{
alert("Connection is closed...");
};
</script>
</body>
</html>
Now, it is time to test websocket as below.
Fig 06 Project Setup |
Other configuration, we also use log4j and maven pom.xml
3.Test Websocket Communication
To test websocket, we just deploy application into Wildlfly. We will deploy our web application in EAR file by create enterprise application project and include the web application.
Fig 04 Deploy Application and test |
Fig 05 Monitor Message to Websocket |
4.Secure Websocket Communication
One more important issue for open communication is security. To secure communication between Websocket, we could SSL to secure the communication. Please refer here
We could setup SSL for client side websocket as below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:rich="http://richfaces.org/rich"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Websocket on Wildlfy</title>
</h:head>
<body>
<rich:panel>
<f:facet name="header">
Write your own custom rich components with built-in AJAX support
</f:facet>
<div >
<h:outputText value="Hello World Websocket." />
</div>
</rich:panel>
<script language="javascript" type="text/javascript">
var wsUri = "wss://localhost:8443/java-ee-07-wsc/hello";
var ws = new WebSocket(wsUri);
ws.onopen = function()
{
alert("Web Socket is connected!!");
var i = 0;
while(i != 5){
ws.send(" Message from Client - Hellllllloxxxxxxxxxx - "+i);
i++
}
};
ws.onmessage = function (evt)
{
var msg = evt.data;
console.log("Message received from server :" + msg);
};
ws.onclose = function()
{
alert("Connection is closed...");
};
</script>
</body>
</html>
We could test the application as below.
Fig 08. Secure Websocket |
5.Reference
In order to create this post, I have referred from below link.
- Create Websocket in Wildfly
- How to build Java WebSocket Applications Using the JSR 356 API
- Create WebSocket Server in Java
No comments:
Post a Comment