websockets jump start

19
WebSockets Jump Start Haim Michael December 20 th , 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 . L i f e M i c h a e l . c o m

Upload: haim-michael

Post on 13-May-2015

1.151 views

Category:

Technology


0 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: 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

Page 2: WebSockets Jump Start

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

Page 3: WebSockets Jump Start

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

Page 4: WebSockets Jump Start

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

Page 5: WebSockets Jump Start

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.

Page 6: WebSockets Jump Start

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.

Page 7: WebSockets Jump Start

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

Page 8: WebSockets Jump Start

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

Page 9: WebSockets Jump Start

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

Page 10: WebSockets Jump Start

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

Page 11: WebSockets Jump Start

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

}

Page 12: WebSockets Jump Start

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

}

Page 13: WebSockets Jump Start

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

}}

}}

}

Page 14: WebSockets Jump Start

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;

Page 15: WebSockets Jump Start

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);};

});

Page 16: WebSockets Jump Start

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>...

Page 17: WebSockets Jump Start

Client Side Code SampleLi fe M

ic hae l .c o

m

Page 18: WebSockets Jump Start

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

Page 19: WebSockets Jump Start

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