WebSockets Jump Start

1,532 views

Published on

Explaining the benefits of using WebSockets, the difference comparing with Ajax and explaining the code we should write on both ends. The server and the client.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,532
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
22
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

WebSockets Jump Start

  1. 1. Haim Michael December 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. LifeMichael.com WebSockets Jump Start
  2. 2. ● 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 LifeMichael.com Table of Content
  3. 3. ● 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. LifeMichael.com Introduction to WebSockets
  4. 4. ● We can easily check whether the web browser supports HTML5 WebSocket API or not. if (window.WebSocket) { … } LifeMichael.com Web Browser Support
  5. 5. ● 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“); We should pass over to the WebSocket constructore the URL address of the web socket server we intend to use. That address should start with 'ws' which stands for Web Sockets. LifeMichael.com Creating WebSocket
  6. 6. ws.onopen = function(event) { ... } This function will be called when the connection is established. LifeMichael.com Callback Functions
  7. 7. ws.onmessage = function(event) { alert(event.data); ... } This function will be called when a message arrives from the server LifeMichael.com Callback Functions
  8. 8. ws.onclose = function(event) { … } This function will be called when the connection is closed LifeMichael.com Callback Functions
  9. 9. ws.postMessage(“message sent to server“); We should call postMessage in order to send data to the server LifeMichael.com Sending Data To The Server
  10. 10. ws.disconnect(); We should call this method in order to close the connection LifeMichael.com Closing The Connection
  11. 11. @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>(); @Override protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) { return new ChatUser(idGenerator.incrementAndGet()); } private final class ChatUser extends MessageInbound { ... @Override protected void onOpen(WsOutbound outbound) { connections.add(this); String message = username + " has joined the chat"; broadcast(message); } LifeMichael.com Server Side Code Sample
  12. 12. @Override protected void onClose(int status) { connections.remove(this); String message = username + " has left the chat"; broadcast(message); } @Override protected void onBinaryMessage(ByteBuffer message) throws IOException { throw new UnsupportedOperationException( "binary messages are not supported"); } @Override protected void onTextMessage(CharBuffer message) throws IOException { // it would be best filter the message // ... String str = username + ": " + message; broadcast(str); } LifeMichael.com Server Side Code Sample
  13. 13. } } LifeMichael.com Server Side Code Sample private void broadcast(String message) { for (ChatUser connection : connections) { try { CharBuffer buffer = CharBuffer.wrap(message); connection.getWsOutbound().writeTextMessage(buffer); } catch (IOException ignore) { // ... } } }
  14. 14. <!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; LifeMichael.com Client Side Code Sample
  15. 15. chat.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); }; }); LifeMichael.com Client Side Code Sample
  16. 16. chat.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> ... LifeMichael.com Client Side Code Sample
  17. 17. LifeMichael.com Client Side Code Sample
  18. 18. ● 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. LifeMichael.com Learning Resources
  19. 19. ● 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. LifeMichael.com Questions & Answers

×