SlideShare a Scribd company logo
Java EE 7 Websocket Chat

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

2014 Micha Kops / www.hascode.com
Table of Contents
●

What we're going to build (I)

●

What we're going to build (II)

●

Prerequisites

●

Creating a new web app

●

Adding the Maven Embedded GlassFish Plugin

●

Websocket Endpoint

●

Chat Message Data Transfer Object

●

Converting Chat Messages

●

Encoder Implementation

●

The Client Side

●

Client DOM Scripts (I)

●

Client DOM Scripts (II)

●

Client DOM Scripts (III)

●

Client HTML (I)

●

Client HTML (II)

●

Build, deploy, run …

●

Tutorial, Sources and Links

2014 Micha Kops / www.hascode.com
What we're going to build (I)

2014 Micha Kops / www.hascode.com
What we're going to build (II)
●

●

●

●

A chat application client using Bootstrap and
jQuery
A user may register with a nickname for a
chatroom from a list of given rooms
Messages in a chat room are pushed to each
subscribed client using web sockets
A user may log out from the chat room

2014 Micha Kops / www.hascode.com
Prerequisites
●

Java 7 JDK

●

Maven 3

●

An IDE of your choice

●

A websockets-capable web
browser

2014 Micha Kops / www.hascode.com
Creating a new web app
●

Using the javaee7-webapp Maven
Archetype

<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

2014 Micha Kops / www.hascode.com
Adding the Maven
Embedded GlassFish Plugin
<plugin>
<groupId>org.glassfish.embedded</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>4.0</version>
<configuration>
<goalPrefix>embedded-glassfish</goalPrefix>
<app>${basedir}/target/${project.artifactId}-${project.version}.war</app>
<autoDelete>true</autoDelete>
<port>8080</port>
<name>${project.artifactId}</name>
<contextRoot>hascode</contextRoot>
</configuration>
<executions>
<execution>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>

2014 Micha Kops / www.hascode.com
Websocket Endpoint
@ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)
public class ChatEndpoint {
private final Logger log = Logger.getLogger(getClass().getName());
@OnOpen
public void open(final Session session, @PathParam("room") final String room) {
log.info("session openend and bound to room: " + room);
session.getUserProperties().put("room", room);
}
@OnMessage
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"))) {
s.getBasicRemote().sendObject(chatMessage);
}
}
} catch (IOException | EncodeException e) {
log.log(Level.WARNING, "onMessage failed", e);
}
}
}

2014 Micha Kops / www.hascode.com
Chat Message Data Transfer
Object
package com.hascode.tutorial;
import java.util.Date;
public class ChatMessage {
private String message;
private String sender;
private Date received;
// getter, setter, toString omitted..
}

2014 Micha Kops / www.hascode.com
Converting Chat Messages
public class ChatMessageDecoder implements Decoder.Text<ChatMessage> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public ChatMessage decode(final String textMessage) throws DecodeException {
ChatMessage chatMessage = new ChatMessage();
JsonObject obj = Json.createReader(new StringReader(textMessage))
.readObject();
chatMessage.setMessage(obj.getString("message"));
chatMessage.setSender(obj.getString("sender"));
chatMessage.setReceived(new Date());
return chatMessage;
}
@Override
public boolean willDecode(final String s) {
return true;
}
}

2014 Micha Kops / www.hascode.com
Encoder Implementation
public class ChatMessageEncoder implements Encoder.Text<ChatMessage> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
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()
.toString();
}
}

2014 Micha Kops / www.hascode.com
The Client Side
●

●

●

●

●

●

●

We're using JavaScript to create the following stuff:
A websocket URL follows this schema:
ws://IP:PORT/CONTEXT_PATH/ENDPOINT_URL e.g
ws://0.0.0.0:8080/hascode/chat/java
A new websocket connection is created using the native WebSocket object e.g.
var wsocket = new WebSocket(‘ws://0.0.0.0:8080/hascode/chat/java’);
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

2014 Micha Kops / www.hascode.com
Client DOM Scripts (I)
var wsocket;
var serviceLocation = "ws://0.0.0.0:8080/hascode/chat/";
var $nickName;
var $message;
var $chatWindow;
var room = '';
function onMessageReceived(evt) {
//var msg = eval('(' + evt.data + ')');
var msg = JSON.parse(evt.data); // 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>');
$chatWindow.append($messageLine);
}
function sendMessage() {
var msg = '{"message":"' + $message.val() + '", "sender":"'
+ $nickName.val() + '", "received":""}';
wsocket.send(msg);
$message.val('').focus();
}

2014 Micha Kops / www.hascode.com
Client DOM Scripts (II)
function connectToChatserver() {
room = $('#chatroom option:selected').val();
wsocket = new WebSocket(serviceLocation + room);
wsocket.onmessage = onMessageReceived;
}
function leaveRoom() {
wsocket.close();
$chatWindow.empty();
$('.chat-wrapper').hide();
$('.chat-signin').show();
$nickName.focus();
}

2014 Micha Kops / www.hascode.com
Client DOM Scripts (III)
$(document).ready(function() {
$nickName = $('#nickname');
$message = $('#message');
$chatWindow = $('#response');
$('.chat-wrapper').hide();
$nickName.focus();
$('#enterRoom').click(function(evt) {
evt.preventDefault();
connectToChatserver();
$('.chat-wrapper h2').text('Chat # '+$nickName.val() + "@" + room);
$('.chat-signin').hide();
$('.chat-wrapper').show();
$message.focus();
});
$('#do-chat').submit(function(evt) {
evt.preventDefault();
sendMessage()
});
$('#leave-room').click(function(){
leaveRoom();
});
});

2014 Micha Kops / www.hascode.com
Client HTML (I)
<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"
id="chatroom">
<option>arduino</option>
<option>java</option>
<option>groovy</option>
<option>scala</option>
</select>
</div>
<button class="btn btn-large btn-primary" type="submit"
id="enterRoom">Sign in</button>
</form>
</div>

2014 Micha Kops / www.hascode.com
Client HTML (II)
<div class="container chat-wrapper">
<form id="do-chat">
<h2 class="alert alert-success"></h2>
<table id="response" class="table table-bordered"></table>
<fieldset>
<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
room</button>
</div>
</fieldset>
</form>
</div>

2014 Micha Kops / www.hascode.com
Build, deploy, run …
●

Simply run: mvn package
embedded-glassfish:run

2014 Micha Kops / www.hascode.com
Tutorial, Sources and Links
●

Please feel free to take a look
at the full tutorial on my blog:
http://www.hascode.com/2013/08/

2014 Micha Kops / www.hascode.com

More Related Content

ODP
Testing RESTful Webservices using the REST-assured framework
Micha Kops
 
ODP
MQTT and Java - Client and Broker Examples
Micha Kops
 
ODP
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
PDF
Java Web Programming [9/9] : Web Application Security
IMC Institute
 
PPT
Request dispatching in servlet
vikram singh
 
PPTX
SERVIET
sathish sak
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PDF
Managing user's data with Spring Session
David Gómez García
 
Testing RESTful Webservices using the REST-assured framework
Micha Kops
 
MQTT and Java - Client and Broker Examples
Micha Kops
 
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Java Web Programming [9/9] : Web Application Security
IMC Institute
 
Request dispatching in servlet
vikram singh
 
SERVIET
sathish sak
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Managing user's data with Spring Session
David Gómez García
 

What's hot (19)

PDF
Servlets intro
vantinhkhuc
 
PDF
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
PPT
Jsp/Servlet
Sunil OS
 
ODP
Spring 4 final xtr_presentation
sourabh aggarwal
 
PPT
Java - Servlet - Mazenet Solution
Mazenetsolution
 
PPT
Servlet life cycle
Venkateswara Rao N
 
PDF
Android webservices
Krazy Koder
 
PDF
Url programming
vantinhkhuc
 
PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPTX
Java Servlets
Emprovise
 
PPT
JSON Rules Language
giurca
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PPTX
Java servlets
yuvarani p
 
DOCX
Servlet
Dhara Joshi
 
PPTX
#3 (Multi Threads With TCP)
Ghadeer AlHasan
 
PDF
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
PPT
AJAX
Gouthaman V
 
PPTX
Servlets
Geethu Mohan
 
PPT
An Introduction To Java Web Technology
vikram singh
 
Servlets intro
vantinhkhuc
 
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 
Jsp/Servlet
Sunil OS
 
Spring 4 final xtr_presentation
sourabh aggarwal
 
Java - Servlet - Mazenet Solution
Mazenetsolution
 
Servlet life cycle
Venkateswara Rao N
 
Android webservices
Krazy Koder
 
Url programming
vantinhkhuc
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Java Servlets
Emprovise
 
JSON Rules Language
giurca
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
Java servlets
yuvarani p
 
Servlet
Dhara Joshi
 
#3 (Multi Threads With TCP)
Ghadeer AlHasan
 
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Servlets
Geethu Mohan
 
An Introduction To Java Web Technology
vikram singh
 
Ad

Similar to Creating a Java EE 7 Websocket Chat Application (20)

PDF
WebSocket
njamnjam
 
KEY
Websockets - DevFestX May 19, 2012
Sameer Segal
 
PDF
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Arun Gupta
 
PPTX
WebSockets in JEE 7
Shahzad Badar
 
PPTX
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
PDF
HTML5 Websockets and Java - Arun Gupta
JAX London
 
KEY
The HTML5 WebSocket API
David Lindkvist
 
PDF
Websocket 1.0
Arun Gupta
 
PPTX
HTML 5 - Web Sockets
Eyal Vardi
 
PPTX
Web sockets in Java
Pance Cavkovski
 
PDF
Creating a Whatsapp Clone - Part I - Transcript.pdf
ShaiAlmog1
 
PDF
Creating a Whatsapp Clone - Part II - Transcript.pdf
ShaiAlmog1
 
PDF
Websocket 101 in Python
Juti Noppornpitak
 
PDF
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
ProcessOne
 
PDF
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
PPT
Get Real: Adventures in realtime web apps
daviddemello
 
PDF
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
PDF
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
 
DOCX
Machine Problem 1: Let's chat
butest
 
PPTX
Programming WebSockets with Glassfish and Grizzly
C2B2 Consulting
 
WebSocket
njamnjam
 
Websockets - DevFestX May 19, 2012
Sameer Segal
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Arun Gupta
 
WebSockets in JEE 7
Shahzad Badar
 
Enhancing Mobile User Experience with WebSocket
Mauricio "Maltron" Leal
 
HTML5 Websockets and Java - Arun Gupta
JAX London
 
The HTML5 WebSocket API
David Lindkvist
 
Websocket 1.0
Arun Gupta
 
HTML 5 - Web Sockets
Eyal Vardi
 
Web sockets in Java
Pance Cavkovski
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
ShaiAlmog1
 
Websocket 101 in Python
Juti Noppornpitak
 
SeaBeyond 2011 ProcessOne - Eric Cestari: XMPP over WebSocket
ProcessOne
 
WebSockets - Realtime em Mundo Conectado
Bruno Borges
 
Get Real: Adventures in realtime web apps
daviddemello
 
WebSocket Push Fallback - Transcript.pdf
ShaiAlmog1
 
Getting Started with WebSocket and Server-Sent Events in Java
Arun Gupta
 
Machine Problem 1: Let's chat
butest
 
Programming WebSockets with Glassfish and Grizzly
C2B2 Consulting
 
Ad

Recently uploaded (20)

PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
GYTPOL If You Give a Hacker a Host
linda296484
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Software Development Methodologies in 2025
KodekX
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
GYTPOL If You Give a Hacker a Host
linda296484
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 

Creating a Java EE 7 Websocket Chat Application

  • 1. Java EE 7 Websocket Chat Creating a Chat Application using Java EE 7, Websockets and GlassFish 4 2014 Micha Kops / www.hascode.com
  • 2. Table of Contents ● What we're going to build (I) ● What we're going to build (II) ● Prerequisites ● Creating a new web app ● Adding the Maven Embedded GlassFish Plugin ● Websocket Endpoint ● Chat Message Data Transfer Object ● Converting Chat Messages ● Encoder Implementation ● The Client Side ● Client DOM Scripts (I) ● Client DOM Scripts (II) ● Client DOM Scripts (III) ● Client HTML (I) ● Client HTML (II) ● Build, deploy, run … ● Tutorial, Sources and Links 2014 Micha Kops / www.hascode.com
  • 3. What we're going to build (I) 2014 Micha Kops / www.hascode.com
  • 4. What we're going to build (II) ● ● ● ● A chat application client using Bootstrap and jQuery A user may register with a nickname for a chatroom from a list of given rooms Messages in a chat room are pushed to each subscribed client using web sockets A user may log out from the chat room 2014 Micha Kops / www.hascode.com
  • 5. Prerequisites ● Java 7 JDK ● Maven 3 ● An IDE of your choice ● A websockets-capable web browser 2014 Micha Kops / www.hascode.com
  • 6. Creating a new web app ● Using the javaee7-webapp Maven Archetype <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies> 2014 Micha Kops / www.hascode.com
  • 7. Adding the Maven Embedded GlassFish Plugin <plugin> <groupId>org.glassfish.embedded</groupId> <artifactId>maven-embedded-glassfish-plugin</artifactId> <version>4.0</version> <configuration> <goalPrefix>embedded-glassfish</goalPrefix> <app>${basedir}/target/${project.artifactId}-${project.version}.war</app> <autoDelete>true</autoDelete> <port>8080</port> <name>${project.artifactId}</name> <contextRoot>hascode</contextRoot> </configuration> <executions> <execution> <goals> <goal>deploy</goal> </goals> </execution> </executions> </plugin> 2014 Micha Kops / www.hascode.com
  • 8. Websocket Endpoint @ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class) public class ChatEndpoint { private final Logger log = Logger.getLogger(getClass().getName()); @OnOpen public void open(final Session session, @PathParam("room") final String room) { log.info("session openend and bound to room: " + room); session.getUserProperties().put("room", room); } @OnMessage 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"))) { s.getBasicRemote().sendObject(chatMessage); } } } catch (IOException | EncodeException e) { log.log(Level.WARNING, "onMessage failed", e); } } } 2014 Micha Kops / www.hascode.com
  • 9. Chat Message Data Transfer Object package com.hascode.tutorial; import java.util.Date; public class ChatMessage { private String message; private String sender; private Date received; // getter, setter, toString omitted.. } 2014 Micha Kops / www.hascode.com
  • 10. Converting Chat Messages public class ChatMessageDecoder implements Decoder.Text<ChatMessage> { @Override public void init(final EndpointConfig config) { } @Override public void destroy() { } @Override public ChatMessage decode(final String textMessage) throws DecodeException { ChatMessage chatMessage = new ChatMessage(); JsonObject obj = Json.createReader(new StringReader(textMessage)) .readObject(); chatMessage.setMessage(obj.getString("message")); chatMessage.setSender(obj.getString("sender")); chatMessage.setReceived(new Date()); return chatMessage; } @Override public boolean willDecode(final String s) { return true; } } 2014 Micha Kops / www.hascode.com
  • 11. Encoder Implementation public class ChatMessageEncoder implements Encoder.Text<ChatMessage> { @Override public void init(final EndpointConfig config) { } @Override public void destroy() { } @Override 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() .toString(); } } 2014 Micha Kops / www.hascode.com
  • 12. The Client Side ● ● ● ● ● ● ● We're using JavaScript to create the following stuff: A websocket URL follows this schema: ws://IP:PORT/CONTEXT_PATH/ENDPOINT_URL e.g ws://0.0.0.0:8080/hascode/chat/java A new websocket connection is created using the native WebSocket object e.g. var wsocket = new WebSocket(‘ws://0.0.0.0:8080/hascode/chat/java’); 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 2014 Micha Kops / www.hascode.com
  • 13. Client DOM Scripts (I) var wsocket; var serviceLocation = "ws://0.0.0.0:8080/hascode/chat/"; var $nickName; var $message; var $chatWindow; var room = ''; function onMessageReceived(evt) { //var msg = eval('(' + evt.data + ')'); var msg = JSON.parse(evt.data); // 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>'); $chatWindow.append($messageLine); } function sendMessage() { var msg = '{"message":"' + $message.val() + '", "sender":"' + $nickName.val() + '", "received":""}'; wsocket.send(msg); $message.val('').focus(); } 2014 Micha Kops / www.hascode.com
  • 14. Client DOM Scripts (II) function connectToChatserver() { room = $('#chatroom option:selected').val(); wsocket = new WebSocket(serviceLocation + room); wsocket.onmessage = onMessageReceived; } function leaveRoom() { wsocket.close(); $chatWindow.empty(); $('.chat-wrapper').hide(); $('.chat-signin').show(); $nickName.focus(); } 2014 Micha Kops / www.hascode.com
  • 15. Client DOM Scripts (III) $(document).ready(function() { $nickName = $('#nickname'); $message = $('#message'); $chatWindow = $('#response'); $('.chat-wrapper').hide(); $nickName.focus(); $('#enterRoom').click(function(evt) { evt.preventDefault(); connectToChatserver(); $('.chat-wrapper h2').text('Chat # '+$nickName.val() + "@" + room); $('.chat-signin').hide(); $('.chat-wrapper').show(); $message.focus(); }); $('#do-chat').submit(function(evt) { evt.preventDefault(); sendMessage() }); $('#leave-room').click(function(){ leaveRoom(); }); }); 2014 Micha Kops / www.hascode.com
  • 16. Client HTML (I) <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" id="chatroom"> <option>arduino</option> <option>java</option> <option>groovy</option> <option>scala</option> </select> </div> <button class="btn btn-large btn-primary" type="submit" id="enterRoom">Sign in</button> </form> </div> 2014 Micha Kops / www.hascode.com
  • 17. Client HTML (II) <div class="container chat-wrapper"> <form id="do-chat"> <h2 class="alert alert-success"></h2> <table id="response" class="table table-bordered"></table> <fieldset> <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 room</button> </div> </fieldset> </form> </div> 2014 Micha Kops / www.hascode.com
  • 18. Build, deploy, run … ● Simply run: mvn package embedded-glassfish:run 2014 Micha Kops / www.hascode.com
  • 19. Tutorial, Sources and Links ● Please feel free to take a look at the full tutorial on my blog: http://www.hascode.com/2013/08/ 2014 Micha Kops / www.hascode.com