Download - WebSockets Jump Start
WebSockets Jump Start
Haim MichaelDecember 20th, 2013
All logos, trade marks and brand names used in this presentation belong to the respective owners.
You can watch the video clip at http://youtu.be/UlGOnYdGqtY.
Li fe M
ic hae l .c o
m
Table of ContentLi fe M
ic hae l .c o
m● Introduction to WebSockets● Web Browser Support● Creating WebSocket● Callback Functions● Sending Data To The Server● Closing The Connection● Server Side Code Sample● Client Side Code Sample● Learning Resources● Questions & Answers
Introduction to WebSockets● HTML5 WebSockets API defines a communication
channel that operates over the web and allows both
direction communication over a single socket.
● Using HTML5 WebSckets API, the web server can
initiate sending data to the client. We no longer need to
implement a client that polls the server.
Li fe M
ic hae l .c o
m
Web Browser Support● We can easily check whether the web browser supports
HTML5 WebSocket API or not.
if (window.WebSocket)
{
…
}
Li fe M
ic hae l .c o
m
Creating WebSocket● The required syntax for creating a new web socket is not
the same on all web browsers.
var ws = new WebSocket(“ws://abelski.com/x“);
Li fe M
ic hae l .c o
m
We should pass over to the WebSocket constructore the URL address ofthe web socket server we intend to use. That address should start with 'ws'which stands for Web Sockets.
Callback Functions
ws.onopen = function(event)
{
...
}
Li fe M
ic hae l .c o
m
This function will be called when the connection is established.
Callback Functions
ws.onmessage = function(event)
{
alert(event.data);
...
}
Li fe M
ic hae l .c o
m
This function will be called when a message arrives from the server
Callback Functions
ws.onclose = function(event)
{
…
}
Li fe M
ic hae l .c o
m
This function will be called when the connection is closed
Sending Data To The Server
ws.postMessage(“message sent to server“);
Li fe M
ic hae l .c o
m
We should call postMessage in order to send data to the server
Closing The Connection
ws.disconnect();
Li fe M
ic hae l .c o
m
We should call this method in order to close the connection
Server Side Code SampleLi fe M
ic hae l .c o
m@WebServlet("/WebSocket")public class WebSocket extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private final AtomicInteger idGenerator = new AtomicInteger(0);private final Set<ChatUser> connections = new HashSet<ChatUser>();
@Overrideprotected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {return new ChatUser(idGenerator.incrementAndGet());
}
private final class ChatUser extends MessageInbound {...@Overrideprotected void onOpen(WsOutbound outbound) {
connections.add(this);String message = username + " has joined the chat";broadcast(message);
}
Server Side Code SampleLi fe M
ic hae l .c o
m@Overrideprotected void onClose(int status) {
connections.remove(this);String message = username + " has left the chat";broadcast(message);
}
@Overrideprotected void onBinaryMessage(ByteBuffer message)
throws IOException {throw new UnsupportedOperationException(
"binary messages are not supported");}
@Overrideprotected void onTextMessage(CharBuffer message)
throws IOException {// it would be best filter the message// ...String str = username + ": " + message;broadcast(str);
}
Server Side Code SampleLi fe M
ic hae l .c o
mprivate void broadcast(String message) {
for (ChatUser connection : connections) {try {
CharBuffer buffer = CharBuffer.wrap(message);connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {// ...
}}
}}
}
Client Side Code SampleLi fe M
ic hae l .c o
m
<!DOCTYPE html><html>
<head> <title>Simple WebSockets Chat</title> <style type="text/css">
... </style></head><body><div> <input type="text" placeholder="enter your message here"
id="user-message"> <div id="chat-messages"></div></div><script type="text/javascript">
var chat = {}; chat.socket = null;
Client Side Code SampleLi fe M
ic hae l .c o
mchat.connect = (function(host) { if ('WebSocket' in window) { chat.socket = new WebSocket(host); } else if ('MozWebSocket' in window) { chat.socket = new MozWebSocket(host); } else { return;
}chat.socket.onopen = function () { document.getElementById('user-message').onkeydown =
function(event) { if (event.keyCode == 13) { chat.sendMessage();
} };};chat.socket.onclose = function () {
document.getElementById('user-message').onkeydown = null;};chat.socket.onmessage = function (message) { messages.add(message.data);};
});
Client Side Code SampleLi fe M
ic hae l .c o
mchat.initialize = function() {
if (window.location.protocol == 'http:') { chat.connect('ws://' + window.location.host + '/websocketproj/WebSocket');
} else { chat.connect('wss://' + window.location.host +
'/websocketproj/WebSocket');}
};
chat.sendMessage = (function() {var message = document.
getElementById('user-message').value;if (message != '') { chat.socket.send(message);
document.getElementById('user-message').value = ''; } });
chat.initialize();
</script>...
Client Side Code SampleLi fe M
ic hae l .c o
m
Learning Resources● You can find a detailed HTML5 free course that covers this
topic at http://abelski.lifemichael.com
● You can find examples for using WebSockets API browsing
at http://www.websocket.org/demos.html.
● Mozilla guide for Web Sockets API at https://developer.mozilla.org/en/docs/WebSockets/Writing_WebSocket_client_applications
● You can find a video clip that explains the code sample this
presentation includes at http://youtu.be/FppM53hsStQ.
Li fe M
ic hae l .c o
m
Questions & Answers● Two courses you might find interesting include
Software Engineering in PHP
more info
Android 4.4 Java Applications Development
more info
HTML5 Cross Platform Mobile Applications
more info
● If you enjoyed my lecture please leave me a comment
at http://speakerpedia.com/speakers/life-michael.
Thanks for your time!
Haim.
Li fe M
ic hae l .c o
m