WebSockets in HTML5 and JBoss

Hi all, its a long time i put my pen in the blog, these days got little busy with my little kid, however i took little time to write about the next-generation client(browser) server communication using WebSockets. In the advent of HTML5 technology all the modern browser are capable of talking to latest servers using WebSockets API.

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server or an Application Server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

All the latest Web Servers and Application Servers has got implementation of WebSockets API as this is been included as part of JavaEE stack.

Let us look at the simple application which i created using JBoss Wildfly 8.1 and Maven

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.websockets</groupId>
	<artifactId>WebSocketsExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>WebSocketsExample</name>
	<description>WebSocketsExample</description>

	<dependencies>
		<dependency>
			<groupId>org.jboss.spec.javax.websocket</groupId>
			<artifactId>jboss-websocket-api_1.0_spec</artifactId>
			<version>1.0.0.Final</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

once all the required and dependent jars got downloaded, let us code with our java server side handler class.
WebSocketHandler.java

/**
 * 
 */
package com.spark.websockets.handler;

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;

/**
 * @author Sony
 *
 */
@ServerEndpoint("/hello")
public class WebSocketHandler {

	@OnMessage
	public String onMessage(String message){
		System.out.println("-------------------------> Received : "+message);
		return "Response from Server ";
	}
	
	@OnOpen
	public void onOpenConnection(Session session){
		System.out.println("---------------------> Web Socket Connection Opened : "+session.getId());
	}
	
	@OnClose
	public void onCloseConnection(CloseReason closeReason){
		System.out.println("--------------> Close Reason : "+closeReason.getReasonPhrase());
	}

}

Once we are done with our java handler, let us start with our html and java script as below.
index.html

<html>
    <head>
        <title>HelloWorld Web sockets</title>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        
        <script language="javascript" type="text/javascript">
            var wsUri = getRootUri() + "/WebSocketsExample/hello";
            function getRootUri() {
                return "ws://" + (document.location.hostname == "" ? "localhost" : document.location.hostname) + ":" +
                        (document.location.port == "" ? "8080" : document.location.port);
            }
            function init() {
                output = document.getElementById("output");
            }
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                    onOpen(evt)
                };
                websocket.onmessage = function(evt) {
                    onMessage(evt)
                };
                websocket.onerror = function(evt) {
                    onError(evt)
                };
                websocket.onclose = function (evt) {
                	cloaseConnection();
                };
            }
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
                doSend(textID.value);
            }
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            }
            function onError(evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            }
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                websocket.send(message);
            }
            function cloaseConnection(){
            	writeToScreen("Closing Connection"+message);
            	websocket.close("closing socket !")
            }
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                output.appendChild(pre);
            }
            
            window.addEventListener("load", init, false);
        </script>
        <h2 style="text-align: center;">Hello World WebSocket Client</h2>
        <br>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
                <input onclick="closeConnection()" value="Close Connection" type="button">
            </form>
        </div>
        <div id="output"></div>
</body>
</html>

finally we are done with our coding part and ready for deployment, please deploy the war file in JBoss Wildfly 8.1 and hit http://localhost:8080/WebSocketsExample/ in the browser and start playing with web sockets.

Happy WebSockets, Happy Coding šŸ™‚

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s