Websocket in Java Part 1: Before JAVA EE7

Learn Recipe: WebSocket using Java

In this first article on websocket we will learn what is websocket and its implementation in JAVA EE6.
In part2 we will see new Java websocket API JSR356

So lets KICKSTART Websockets.

Precook : Few tech facts

What is Websocket ? A brief introduction

  • New protocol introduced in HTML5 specification (RFC 6455)
  • Leverages HTTP upgrade technology
  • Upgrade HTTP to Websocket
  • Once connection established no headers, cookies required
  • A full duplex communication
  • Independent  message can be sent in both direction (server-client).
  • Supports binary data
  • Since uses TCP/HTTP, thus work on same port
  • Also support secure connection ie both ws:// or wss:// supported.
  • Intended to use for: Chat Applications,Interactive games,Media Streaming, Notifications,server push…
  • Browser Support : (All leading browser supports)Firefox,Chrome,Safari,IE10,etc…
  • Server support: Apcahe Tomcat 7,Oracle Glassfish3,Oracle Glassfish4
    • For JAVA EE 6: Third party API available.( Tomcat7 /Glassfish3 /Jwebsocket / Lightstramer )
    • For JAVA EE7: Implemented (JSR356) Java API for Web Socket.

Let’s Cook : Simple Eco application

Continue reading


Get users IP

This code example shows how to obtain the IP address of the user that calls the server.
The Request object has a few neat methods to get information about the call and about the caller, and one of them is named getRemoteAddr() which returns the IP address of the calling computer.
In the example below we print out the IP address on a blank html-page.

import java.io.*;
import java.util.Enumeration;

import javax.servlet.*;
import javax.servlet.http.*;

* Example Servlet
* @author http://www.javadb.com
public class ExampleServlet extends HttpServlet {

/** Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


//Print out the IP address of the caller


/** Prints out the start of the html page
* @param out the PrintWriter object
private void printPageStart(PrintWriter out) {

out.println("Example Servlet of how to display users IP-address");


/** Prints out the end of the html page
* @param out the PrintWriter object
private void printPageEnd(PrintWriter out) {