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.

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://0.0.0.0:8080/hascode/chat/java

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()…

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.

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 beIETF RFC 6455

This entry was posted
on Tuesday, August 13th, 2013 at 9:16 pm and is filed under Enterprise, Java.
You can follow any responses to this entry through the RSS 2.0 feed.
You can skip to the end and leave a response. Pinging is currently not allowed.

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:

org.eclipse.jetty
jetty-maven-plugin
${jettyVersion}

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

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:

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.

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

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 !

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 http://maven.apache.org 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!

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

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: https://github.com/atao60/javaee7-websocket-chat.

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

sure! You should add some authentication for the initial handshake, enable SSL e.g. by adding something like this to your web.xml:<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

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://).

sure! You should add some authentication for the initial handshake, enable SSL e.g. by adding something like this to your web.xml:<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>

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://).

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 :)

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

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.

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.

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.

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/”;

Hi,
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