Creating a Chat Application using Java EE 7, Websockets and GlassFish 4

August 13th, 2013 by

Java EE 7 is out now and so I was curious to play around with the new specifications and APIs from in this technology stack.

That’s why I didn’t hesitate to add yet another websocket-chat tutorial to the existing ones on the internet in favour of gathering some experience with this technology and a possible integration using a GlassFish 4 server, the new Java API for JSON Processing for data serialization combined with custom websocket encoders/decoders and finally adding some Bootstrap and jQuery on the client side.


The final chat application.

The final chat application.


We need the following stuff to build and run the following application:

Creating the new Project

You should simply use the Java EE 7 Webapp Archetype here so that your final pom.xml could look similar to this one (shortened):


Maven Embedded GlassFish Plugin

Adding the following snippet allows us to quickly download and start up a full GlassFish 4 instance with our application deployed by running one simple Maven goal.

Big thanks @resah for pointing out at one issue that got me initially (EMBEDDED_GLASSFISH-142) but is no problem if you’re using the following plugin configuration


Afterwards we’re able to startup the application server by running the following command:

mvn embedded-glassfish:run

The Websocket Endpoint

This is our endpoint implementation. Some short facts here about the implementation.

  • @ServerEndpoint defines a new endpoint – the value specifies the URL path and allows PathParams as we’re used know from JAX-RS.
  • So value=”/chat/{room}” allows the client to open a websocket connection to an URL like ws://<IP>:<PORT>/<CONTEXT_PATH>/chat/room .. e.g. ws://
  • The value in curly braces may be injected as a path parameter in the lifecycle callback methods in the endpoint using javax.websocket.server.PathParam
  • In addition to the URL schema, we’re specifying an encoder and a decoder class. We need this because we’re using a custom DTO object to pass our chat data between server and client
  • When a client opens the first connection to the server, he passes the chat-room he wants to enter as a path-parameter and we’re storing this value in the user properties map using session.getUserProperties()..
  • Now when a chat participant posts a new message over the tcp connection to the server, we’re iterating over all open session, and each session that is assigned to the room the session/message is bound to, receives the decoded and re-encoded message
  • If we wanted to send a simple text or binary message we could have used session.getBasicRemote().sendBinary() or session.getBasicRemote().sendText()
package com.hascode.tutorial;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.EncodeException;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)
public class ChatEndpoint {
	private final Logger log = Logger.getLogger(getClass().getName());
	public void open(final Session session, @PathParam("room") final String room) {"session openend and bound to room: " + room);
		session.getUserProperties().put("room", room);
	public void onMessage(final Session session, final ChatMessage chatMessage) {
		String room = (String) session.getUserProperties().get("room");
		try {
			for (Session s : session.getOpenSessions()) {
				if (s.isOpen()
						&& room.equals(s.getUserProperties().get("room"))) {
		} catch (IOException | EncodeException e) {
			log.log(Level.WARNING, "onMessage failed", e);

ChatMessage Data-Transfer-Object

This is the DTO we’re using to transfer the chat data bidirectional over the TCP connection.

package com.hascode.tutorial;
import java.util.Date;
public class ChatMessage {
	private String message;
	private String sender;
	private Date received;
	// getter, setter, toString omitted..

Converting ChatMessages

These are the encoder and the decoder implementations that are referenced in the @ServerEndpoint properties and that allow us to convert incoming or outgoing data between ChatMessages and the JSON format.

Decoder Implementation

The following decoder converts incoming chat message strings to out ChatMessage POJO.

We’re using the new Java API for JSON Processing (JSR353) here to pass data from the JSON format to the ChatMessage.

The willDecode() method allows us to specify if our decoder is able to handle the incoming data .. in our case this is always true ;)

package com.hascode.tutorial;
import java.util.Date;
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
public class ChatMessageDecoder implements Decoder.Text<ChatMessage> {
	public void init(final EndpointConfig config) {
	public void destroy() {
	public ChatMessage decode(final String textMessage) throws DecodeException {
		ChatMessage chatMessage = new ChatMessage();
		JsonObject obj = Json.createReader(new StringReader(textMessage))
		chatMessage.setReceived(new Date());
		return chatMessage;
	public boolean willDecode(final String s) {
		return true;

Encoder Implementation

This encoder does the opposite – converting a ChatMessage to a JSON string again using the Java API for JSON Processing and its shiny new JSON builder.

package com.hascode.tutorial;
import javax.json.Json;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
public class ChatMessageEncoder implements Encoder.Text<ChatMessage> {
	public void init(final EndpointConfig config) {
	public void destroy() {
	public String encode(final ChatMessage chatMessage) throws EncodeException {
		return Json.createObjectBuilder()
				.add("message", chatMessage.getMessage())
				.add("sender", chatMessage.getSender())
				.add("received", chatMessage.getReceived().toString()).build()

Bootstrap, Javascript .. the Client Side of Life…

Finally we’re adding the following index.html to the src/main/webapp directory (shortened, please feel free to have a look a the tutorial sources for the full code)

There are only three interesting API calls that we should remember here – the rest of the javascript adds some functions to the user interface etc …

  • A websocket URL follows this schema: ws://IP:PORT/CONTEXT_PATH/ENDPOINT_URL e.g ws://
  • A new websocket connection is created using the native WebSocket object e.g. var wsocket = new WebSocket(‘ws://’);
  • Registering a callback function to receive incoming messages from the server goes like this: wsocket.onmessage = yourCallbackFunction;
  • Sending a message to the server is done by wsocket.send() .. pass a string, binary data .. whatever you like ..
  • Closing a connection is simply done by wsocket.close()
  • There is a lot of useful information that I did not add to this tutorial from keepalive-pings to the handshake protocol and other features .. one good starting point for detailed information about websockets might be IETF RFC 6455
<!DOCTYPE html>
<html lang="en">
	var wsocket;
	var serviceLocation = "ws://";
	var $nickName;
	var $message;
	var $chatWindow;
	var room = '';
	function onMessageReceived(evt) {
		//var msg = eval('(' + + ')');
		var msg = JSON.parse(; // native API
		var $messageLine = $('<tr><td class="received">' + msg.received
				+ '</td><td class="user label label-info">' + msg.sender
				+ '</td><td class="message badge">' + msg.message
				+ '</td></tr>');
	function sendMessage() {
		var msg = '{"message":"' + $message.val() + '", "sender":"'
				+ $nickName.val() + '", "received":""}';
	function connectToChatserver() {
		room = $('#chatroom option:selected').val();
		wsocket = new WebSocket(serviceLocation + room);
		wsocket.onmessage = onMessageReceived;
	function leaveRoom() {
	$(document).ready(function() {
		$nickName = $('#nickname');
		$message = $('#message');
		$chatWindow = $('#response');
		$('#enterRoom').click(function(evt) {
			$('.chat-wrapper h2').text('Chat # '+$nickName.val() + "@" + room);
		$('#do-chat').submit(function(evt) {
	<div class="container chat-signin">
		<form class="form-signin">
			<h2 class="form-signin-heading">Chat sign in</h2>
			<label for="nickname">Nickname</label> <input type="text"
				class="input-block-level" placeholder="Nickname" id="nickname">
			<div class="btn-group">
				<label for="chatroom">Chatroom</label> <select size="1"
			<button class="btn btn-large btn-primary" type="submit"
				id="enterRoom">Sign in</button>
	<!-- /container -->
	<div class="container chat-wrapper">
		<form id="do-chat">
			<h2 class="alert alert-success"></h2>
			<table id="response" class="table table-bordered"></table>
				<legend>Enter your message..</legend>
				<div class="controls">
					<input type="text" class="input-block-level" placeholder="Your message..." id="message" style="height:60px"/>
					<input type="submit" class="btn btn-large btn-block btn-primary"
						value="Send message" />
					<button class="btn btn-large btn-block" type="button" id="leave-room">Leave

Build, Deploy, Run…

Now we’re ready to build and deploy our application. If you’re using the embedded-glassfish-plugin your simply need to run

mvn package embedded-glassfish:run

Alternatively upload the application to your GlassFish instance and use hascode as context path (or modify the path in the index.html according to your context path!).

Finally you should be able to load the chat application at the following URL: http://localhost:8080/hascode and it should look similar to this screenshot:

The final chat application.

The final chat application.


This is our chat in action – I’ve used two browser instances – one Chrome, one Firefox here to simulate two chat participants: Screencast on YouTube.

Tutorial Sources

Please feel free to download the tutorial sources from my Bitbucket repository, fork it there or clone it using Git:

git clone

Direct Download

For those of you who do not want to build the application by themselves, I’ve added the war file as a direct download here:


I’ve added the following presentation on my slideshare account:

Client Implementation in Java

Please feel free to have a look at my article “Creating different Websocket Chat Clients in Java” for a client implementation in Java.


Websocket Chat Articles

I have written other tutorials about websocket server and client implementations, please feel to read further:

Article Updates

  • 2018-06-01: Embedded YouTube video removed (GDPR/DSGVO).
  • 2016-10-29: Link to Go implementation of websocket chat added.
  • 2014-11-09: Article about websocket client implementation in Java linked.

Tags: , , , , , , , , , , , , ,

65 Responses to “Creating a Chat Application using Java EE 7, Websockets and GlassFish 4”

  1. arr zee Says:

    wat jars i have to add to run it full with easee

  2. micha kops Says:

    the app can be downloaded here: or do you need information regarding libraries/dependencies?

  3. admin Says:

    cann’t download the war in china?

  4. micha kops Says:

    Possibly a temporary error in Bitbucket’s CDN .. does the problem still exist?

  5. Zavael Says:

    hi, i tried your example on jetty but its somehow not working.. it signs me in the room, but when I want to send message, its doing nothing..
    To make it work on jetty i just added plugin to pom to the project from git repo on bitbucket:


    with jetty version 9.0.7.v20131107
    can you help me solve the problem? thanks.. and by the way, great article :)

  6. micha kops Says:

    Jetty is a servlet container but not a Java EE application server therefore the war file produced won’t work that way when deployed on a normal servlet container. If you’d like to experiment with websockets on a jetty server, perhaps one of the following links may help you here:

    Alternatively if you’d like to try something completly different without a classical servlet container or application server, please feel free to have a look at my blog article “Creating a Websocket Chat Application with Vert.x and Java

  7. prideloki Says:

    I did this and but stuck in the chatting room.
    when I entered a message, the message didn’t show up.
    I use a NetBean and Glassfish.

  8. vandiedakaf Says:

    If this tutorial does not work for you then change serviceLocation (in index.html):

    var serviceLocation = “ws://localhost:8080/hascode/chat/”;

  9. Ashwinikumar Says:

    Great, thanks, it worked on Glassfish. There was a slight glitch for me, in the HTML – here is what I did -

    Added in head,

    and changed javascript method to jQuery(document).ready(function()

  10. Psuryawanshi Says:

    I have downloaded source code & done successfully build n deploy only with Maven 3 not on higher version. once it got deployed started app with http://localhost:8080/hascode/ url.

    it enters into room with login but not able to send sms as does nothing on send button click. when checked it was showing error on browser console as WebSocket is already in CLOSING or CLOSED state.

    Please advice how to take it further.

  11. Jaz Says:


    Many thanks for an excellent post!

    I have downloaded the example WAR file and deployed it to my GlassFish 4.0 Server, unfortunately I simply cannot get it to work.

    I am using Firefox which reports it is unable to connect to connect to the server as follows:

    “Firefox can’t establish a connection to the server at ws://”

    I see no problems in the server log which reports the WAR file has been successfully deployed.

    Would really appreciate any ideas on why it is not working or how I can explore further,

    Many thanks!

  12. Billel Says:

    The publication list of messages does not work in chat (Enter your message … and always empty) even though sending multiple message.

    Thank you to correct or tell us how to do it (as if this feature has been removed)
    La liste de publication des messages ne fonctionne pas dans le chat (Enter your message… et toujours vide) même si en envoi plusieurs message.

    Merci de corrige ou de nous dire comment le faire (comme si cette fonctionnalité a été supprimé)

  13. Kristoff Says:

    Hey Psuryawanshi
    I have the same error that You had:
    WebSocket is already in CLOSING or CLOSED state

    Any luck with that?

  14. Kristoff Says:

    Update :)

    problem was in serviceLocation param.

    var serviceLocation = “ws://”; <- not good

    var serviceLocation = "ws://" + + "/ChatRoomProject/chat/"; <- ok in my case.

    After this change everything works fine.

    Hope that help :)

  15. Mangal Dev Says:

    Awesome… Cool Stuff. It is so complete. Just downloaded and ran in a single shot.

    @Kristoff : Thanks dude. I was getting the same issue and with your change its working perfectly :)

  16. Bruno S Says:

    Man, perfect job! Nice tutorial…

    I’m starting learn about websockets, can u say an good link with some explanations? To help me understand websockets and if u know an tuto that uses primfaces, JSF… with websockets..

  17. arrhe Says:

    I downloaded war and deployed in tomcat server made changes in index.jsp var serviceLocation = “ws://””/hascode/chat/”;.Even after the changes it says 404 exception.

  18. micha kops Says:

    Hi arrhe,

    you can’t run a Java EE application on a Tomcat servlet container – you need to use an application server instead.

    If you want to use websockets on a Tomcat server you can find more information here:

    A snippet:

    If you’re interested in another solution without using the Java EE stack but using Vert.x, please feel free to have a look at the following article of mine: “Creating a Websocket Chat Application with Vert.x and Java

  19. arrhe Says:

    Hi Micha kops,
    I’m a new bee can please tell what excatly do i need to do.I tried to create a dynamic web project and replaced the files available in git but still it throwing 404 exception “localhost:8080/chaton/wsapp/WsChatServlet” chat on is my application name,wsapp is my package name.

  20. micha kops Says:

    Hi Arrhe,

    could you please share your code on some public repository please – maybe I can be a better help then :)

  21. arrhe Says:

    Hi micha kops,
    I need something which should be server independent.

  22. arrhe Says:

    i Micha kops,
    I have commited it to git repository and the url for it is the application should be server independent. Thank you.

  23. Neeraj Says:

    Hi sir,

    I downloaded your war file and i added this library to my login project and i am using Apache tomcat server Oracle 10G database.. while running this http://localhost/8088/hascode i am getting “This webpage is not available” error.
    Index page is not editable.Please help how to run this file.
    Thanks in advance

  24. micha kops Says:

    Hi Neeraj,

    you can’t run a Java EE application on a simple servlet container like Tomcat – please select an appropriate application server ( or chose an alternative implementation that does not depend on Java EE .. e.g. Tomcat’s implementation of the websocket spec.



  25. micha kops Says:

    arrhe, neeraj: I think I’ll be adding a full example using tomcat or jetty .. please be patient :)

  26. arrhe Says:

    Hi Micha kops,
    Can i get the tomcat version .

  27. FR Says:

    Hi Micha,
    Have you ever had a chance to start in the example under Tomcat? I am trying to do that port myself so if you have some pointers I would really appreciate.

  28. micha kops Says:

    Hi FR,

    I’ve just digged through the Tomcat docs and the websocket examples shipped with Tomcat since version 7 http://localhost:8080/examples/websocket/chat.xhtml sources ->

    There’s a tutorial here that might be a help: .. might need to alter the endpoint creation to work with the single threaded model for an endpoint.

  29. Beginner Says:

    I would like to run the project on eclipse. I imported it but know I don´t know how to run it. It would be great if someone could give a step-by-step instructions to run the code. Sorry if it seems to naive, I am strating from scatch (as we all do …).
    THank already !

  30. micha kops Says:

    No problem :)

    But you need to install Maven to manage the dependencies (you really do not want to handle this for youself), so please consider downloading and installing Apache Maven from or use the Maven Plugin for Eclipse.

    If you’ve downloaded Maven, simply run the following command in the project directory to create Eclipse IDE project files:
    mvn eclipse:eclipse this might take a while because there’s a huge bunch of dependencies downloaded, afterwards you may import it in Eclipse using “Import > Existing Project”

    Otherwise if your Eclipse IDE has Maven Support then you may directly import the plugin with “Import > Existing Maven Project”.

    Please feel free to keep me up to date if it is working for you or if you need assistance!



  31. rajngla Says:

    Hi Micha,

    I’m going through your example, and I have 1 question. In your program you hardcoded values of the rooms (java, arduino, groovy, scala). My question would be, is there any way of having those values stored in the java list (or any other collection) and somehow passed to the .html where it would be dynamically added? So I would like to have something like for each loop in .html and print all available rooms from that list. I’m pretty new to all this so excuse me if the question sounds dumb XD

    Btw great tutorial thank you very much for that :)

  32. micha kops Says:

    Hi Rajngla,

    you could create a data-transfer-objects similar to ChatMessage e.g. ChatRoomList and push this list to the client when new chat rooms are created or deleted.

  33. ashif Says:

    iam face same proble………..404 not found

  34. atao60 Says:


    I just extended your example to run with Wildfly too and to be available as a runnable fatjar, either
    with Glassfish or Wildfly, using Payara-Micro, Capsule and Wildly-Swarm. The code is available
    on Github:

  35. Javier Says:

    Me fue de mucha ayuda, gracias por compartir…

  36. micha kops Says:

    Gracias de nada!

  37. Jamie Says:

    Hi first off great guide :)

    I just have a question is it possible to display active members that are in the chat room, hence a live list that updates when people leave or join so members can see whose online ?

    any idea how you would go about this if its possible ?

  38. Jamie Mulvaney Says:

    Hye wondering if it would be possible to display active members in a chat room ?

    just a simple list that updates when people leave or join

    is this possible if so any ideas on how to make it work ?

  39. micha kops Says:

    You could use the information from the opened sessions to produce a second data stream to update a simple user list in the client view.

  40. Jamie Says:

    Hi Again I have been working with your tutriol for a while now but have ran into a problem, I am trying to throw it up on my localhost using xampp so I can build a simple login for the site but the websockets are guess me problems

    So i download the default code just to see I could get that to work but still no look

    I can seem to get the to work at all

    I get the error

    WebSocket connection to ‘ws://localhost/ChatSystem/chat/arduino’ failed: Error during WebSocket handshake: Unexpected response code: 404

    Then I login and if I try and type I get this error

    WebSocket is already in CLOSING or CLOSED state.

    Any help you would be great

    I know its a problem with the var serviceLocation I just dont know what to change it to ?

  41. Jamie Mulvaney Says:

    Hi again, I am currently using the default version of your code provided above because I want to add a php login etc to the system

    So I put the project in my xampp/htdocs folder so I can deploy it on my localhost

    Which all went fine I then ran into the problem of the chat not working because the serviceLocation was off it just kept giving me a 404

    I tried changing it to:

    var serviceLocation = “ws://localhost/Chatsystem/chat/”;

    But still got the same error I dont know why and I missing something somewhere else in the code ?

  42. micha kops Says:

    Hi Jamie,

    have you set the right context-path and port in your service location?

  43. Steve Says:

    Can we turn this into a private chatting application?

  44. Micha Kops Says:

    Hi Steve,

    sure! You should add some authentication for the initial handshake, enable SSL e.g. by adding something like this to your web.xml:

    Then create a auth token on the server and use it in the following TCP communication between client and server (and don’t forget to use wss:// instead of ws://).

  45. Micha Kops Says:

    Hi Steve,

    sure! You should add some authentication for the initial handshake, enable SSL e.g. by adding something like this to your web.xml:

    Then create a auth token on the server and use it in the following TCP communication between client and server (and don’t forget to use wss:// instead of ws://).

  46. Stanley Obrien Says:

    First off, amazing tutorial! :D I have the same problem as Jamie but instead of the 404, I can’t seem to see the messages that I type while on chat…I’ve tried the several approaches highlighted here i.e. changing the service location from what it was to the one Jamie had but it still doesn’t seem to work. I’m at a loss here. I don’t really understand what you mean by if we have set the right context path and port. Would you please clarify? Many thanks :)

  47. nouha Says:

    Hi ,
    thanks for this great tutorial , I want to change this code to make it sending images what can I do ??
    PS: I tried to convert the image on string (base64) and send it on message of ChatMessage but I get error message much bigger than than size of buffer

  48. AKKI Says:

    Hi,I have tried ur code it allowed me login but on send message it was not diaplaying anytrhing means nothing gonna happens on click send button.
    I read the comments posted over here but still not getting any solution.If anyone can help me to solve this error it would be great.Thanks In advance.

  49. Subhajit Seth Says:

    Hi,All I have tried the code fully it allowed me to logged in but on send message it was not displaying anything after clicking on the send button
    I read the comments posted over here but still not getting any solution.If anyone can help me to solve this error it would be great.Thanks In advance.

  50. edsontofolo Says:

    oh man! thk u for the great example! was exactly what i needed

  51. Micha Kops Says:

    Thanks! You’re welcome! :)

  52. s Says:

    Thanks dude, it helped me a lot! :-)

  53. ashwini Says:

    hi, i am trying this code… i am run it on chrome and Firefox browsers it will works as client but not send msg from server to client and doesn’t throw any exception..and i have used tomcat server…
    can you send me pom file using tomcat dependency????it will throw this warning..

    WARNING: [SetContextPropertiesRule]{Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:javaee7-websocket-chat’ did not find a matching property.

  54. Tsotne Shonia Says:

    For all the people who don’t get any response after clicking the send button, make sure your context path is set correctly.
    The provided code uses “/hascode” as context path.
    If you use Netbeans, this can be done simply by right clicking the project -> properties -> run -> set “/hascode” (without the quotes) in Context Path.

    Also, in my case, the specified ip in the client wasn’t reaching the server.
    I replaced the line (in index.html) like so :
    var serviceLocation = “ws://localhost:8080/hascode/chat/”;

    After both modifications, everything worked fine

  55. sani Says:

    sir i put code and change the var server location but not work not sigin not leave
    i also add 1.0 .war file

  56. Micha Kops Says:

    Hi sani,

    any diagnostic input? errors? logs? js-console?



  57. TW Says:

    great example!!
    could i commmit github?

    my project can run on tomcat

  58. Zura Says: i have problem with this code , plz see following question thnx

  59. Jan Says:

    The 404 means that very probably, that the path is wrong, look at the following line
    @ServerEndpoint(value = “/chat/{room}”, encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)

    * Adjust the value to the right path, if you are using the code in Eclipse
    * or adjust the deployment path, if you deployed the war file

    so that that path matches.

    I built a new eclipse project with name “Webchat” and put the code there. At the begin O got 404 too, then, I realised that

    application was running as http://localhost:8080/WebChat/
    but the value in the given code was – > (value = “/chat/{room}”
    Thus the path did not match

    updated -> value = “/chat/{room}”, to – > value = “/{room}”,

    Every things worked/work

    Kind regards,

  60. jerry Says:

    thanks thats nice one, its really helpful but you hide the getsender()and getRecieved().

  61. Micha Kops Says:

    Hi Jerry,
    yes, I’ve ommitted this trivial code in the tutorial but if you follow the link to the “Tutorial Sources” you’ll find the complete source code … here is the link to the ChatMessage class including its setters and getters:


  62. Raj Says:

    When I enter the message and submit, where the message is going

  63. Micha Kops Says:

    It’s send over the websocket connection to the backend server.

  64. Nick Says:

    Thanks! Good job

  65. Guest Says:

    Hi, Micha! Please help me. I use NetBeans IDE. How can I run this command “mvn embedded-glassfish:run”, and where can i do this?