SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Websockets
         Sameer Segal


Artoo - Technology to the Rescue
          www.artoo.in
@artootrills
http://sameersegal.github.com

Presentation: Websockets & Projects: KnockOutTweety
KnockOut Tweety
              http://kot.artoo.in




http://sameersegal.github.com/KnockOutTweety/
Image Credit: http://www.lewisbenge.net/wp-content/uploads/2011/08/image_634393295480776281.png
Image Credit: http://www.lewisbenge.net/wp-content/uploads/2011/08/image_634393295481826341.png
HTTP vs Websockets
HTTP
// Request
GET /home HTTP/1.1
Host: trial.artoo.in
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML,
like Gecko) Chrome/19.0.1084.46 Safari/536.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: .......

// Response
HTTP/1.1 200 OK
Date: Sat, 19 May 2012 06:04:24 GMT
Server: Play! Framework;master-jenkins-Artoo-Play-15;prod
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
Set-Cookie: .....
.
.
.
Via: 1.1 artoo.in
Vary: Accept-Encoding
Content-Encoding: gzip
Connection: close
Transfer-Encoding: chunked
Websocket
// Request
GET wss://socket.artoo.in/chat?
username=admin&clientId=0782cd45-307d-414b-8efa-b2156253b6xx HTTP/1.1
Origin: https://trial.artoo.in
Cookie: ...
__utma=27942636.1788801618.1323048033.1337320289.1337406233.265;
__utmb=27942636.7.10.1337406233; __utmc=27942636;
__utmz=27942636.1337136927.261.12.utmcsr=google|utmccn=(organic)|
utmcmd=organic|utmctr=(not%20provided)
Connection: Upgrade
Sec-WebSocket-Extensions: x-webkit-deflate-frame
Host: socket.artoo.in
Sec-WebSocket-Key: ego8R97Ruc3d5RPwRhhtzw==
Upgrade: websocket
Sec-WebSocket-Version: 13


// Resonse
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: CEbdJJgOTp1ZCcx6+RZTngrI5Ek=
HTTP                                                     Websocket
                                                             GET wss://socket.artoo.in/chat?
GET /home HTTP/1.1                                           username=admin&clientId=0782cd45-307d-414b-8efa-b2156253b6xx
Host: trial.artoo.in                                         HTTP/1.1
Connection: keep-alive                                       Origin: https://trial.artoo.in
Cache-Control: max-age=0                                     Cookie: ...
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4)   __utma=27942636.1788801618.1323048033.1337320289.1337406233.26
AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46    5; __utmb=27942636.7.10.1337406233; __utmc=27942636;
Safari/536.5                                                 __utmz=27942636.1337136927.261.12.utmcsr=google|
Accept: text/html,application/xhtml+xml,application/         utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)
xml;q=0.9,*/*;q=0.8                                          Connection: Upgrade
Accept-Encoding: gzip,deflate,sdch                           Sec-WebSocket-Extensions: x-webkit-deflate-frame
Accept-Language: en-US,en;q=0.8                              Host: socket.artoo.in
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3               Sec-WebSocket-Key: ego8R97Ruc3d5RPwRhhtzw==
Cookie: .......                                              Upgrade: websocket
                                                             Sec-WebSocket-Version: 13

HTTP/1.1 200 OK
Date: Sat, 19 May 2012 06:04:24 GMT
Server: Play! Framework;master-jenkins-Artoo-Play-15;prod
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
Set-Cookie: .....                                            HTTP/1.1 101 Switching Protocols
.                                                            Connection: Upgrade
.                                                            Upgrade: websocket
.                                                            Sec-WebSocket-Accept: CEbdJJgOTp1ZCcx6+RZTngrI5Ek=
Via: 1.1 artoo.in
Vary: Accept-Encoding
Content-Encoding: gzip
Connection: close
Transfer-Encoding: chunked




                                                                                  One time
                 Everytime                                         (2 bytes of overhead for every
                                                                              message)
"Reducing kilobytes of data to 2 bytes…and
reducing latency from 150ms to 50ms is far
more than marginal. In fact, these two factors
alone are enough to make Web Sockets
seriously interesting to Google."

- Ian Hickson (Google’s HTML5 Spec Lead)
Specs
• Based on TCP but not true TCP socket
• ws:// or wss://
• Full-Duplex
 • Both UTF-8 strings and binary frame can
    be sent in any direction
• More at http://dev.w3.org/html5/
  websockets/
Use?
JS         Regular Javascript                      Client-Side
     var socket = null;
     var socketUrl = “ws://localhost:8080/feed”;
     $(function(){

           socket = new WebSocket(socketUrl);

           socket.onopen = function(event) {

           }

           socket.onmessage = function(event) {

           }

           socket.onclose = function(event) {

           }
     });
JS   jquery-websocket
     http://code.google.com/p/jquery-websocket/
                                                  Client-Side
Android Java Websocket         https://github.com/TooTallNate/Java-WebSocket
                                                                                                               Client-Side
                                                             	   	   @Override
    public class SampleSocket extends WebSocketClient {      	   	   public void onMessage(String message) {
                                                             	   	   	    Chat chat = Chat.fromJSON(message);
	   	   private   Context context;
	   	   private   boolean connected = false;                 	   	   	    if (chat != null) {
	   	   private   Handler h = new Handler();                 	   	   	    	    ContentValues values = new ContentValues();
	   	   private   Runnable r = new Runnable() {
                                                             	   	   	    	       switch (chat.event) {
	   	   	    @Override                                       	   	   	    	       case ONLINE:
	   	   	    public void run() {
	   	   	    	    try {                                      	   	   	    	       	    break;	    	   	   	     	
	   	   	    	    	    Chat chat = new Chat();               	   	   	    	       case OFFLINE:
	   	   	    	    	    chat.event = event_type.STAY_ALIVE;
	   	   	    	    	    if (connected) {                      	   	   	    	       	    break;	    	   	   	     	
	   	   	    	    	    	    send(chat.toJSON());             	   	   	    	       case USER:
	   	   	    	    	    }
	   	   	    	    } catch (IOException e) {                  	   	   	    	       	    break;
	   	   	    	    	    e.printStackTrace();                  	   	   	    	       case MESSAGE:
	   	   	    	    }
                                                             	   	   	    	       	    break;
	   	   	    	     h.postDelayed(r, 10000);                  	   	   	    	       default:
	   	   	    }
	   	   };                                                   	   	   	    	       }

	   	   public SampleSocket(Context context, URI serverUri) {                 	   // Insert / Update into DB
	   	   	    super(serverUri);                             	     	   	    }
	   	   	    this.context = context;
                                                           	     	   }
	   	   	    // Sending keep alive messages
	   	   	    h.postDelayed(r, 5000);                       	     	   @Override
	   	   }                                                  	     	   public void onOpen() {
                                                           	
	   	   public SampleSocket(Context context, URI serverUri,	     	   }
	   	   	    	    WebSocketDraft draft) {
	   	   	    super(serverUri, draft);                      	     	   @Override
	   	   	    this.context = context;                       	     	   public void onClose() {
	   	   }
                                                           	     	   }

                                                             	   	   @Override
                                                             	   	   public void onIOError(IOException ex) {
                                                             	   	   }
Android                                    Client-Side



  Activity 1

               Use Messenger


                                Service
  Activity 2

                               WebSocket
Java       jquery-websocket
           http://jwebsocket.org/
                                                                                                  Server-Side
       public class JWebSocketTokenListenerSample implements WebSocketTokenListener {

           private static Logger log = Logging.getLogger(JWebSocketTokenListenerSample.class);

           public void processOpened(WebSocketEvent aEvent) {
             log.info("Client '" + aEvent.getSessionId() + "' connected.");
           }

           public void processPacket(WebSocketEvent aEvent, WebSocketPacket aPacket) {
             // here you can process any non-token low level message, if desired
           }

           public void processToken(WebSocketTokenEvent aEvent, Token aToken) {
             log.info("Client '" + aEvent.getSessionId() + "' sent Token: '" + aToken.toString() + "'.");
             // here you can interpret the token type sent from the client according to your needs.
             String lNS = aToken.getNS();
             String lType = aToken.getType();

               // check if token has a type and a matching namespace
               if (lType != null && "my.namespace".equals(lNS)) {
                 // create a response token
                 Token lResponse = aEvent.createResponse(aToken);
                 if ("getInfo".equals(lType)) {
                   // if type is "getInfo" return some server information
                   lResponse.put("vendor", JWebSocketConstants.VENDOR);
                   lResponse.put("version", JWebSocketConstants.VERSION_STR);
                   lResponse.put("copyright", JWebSocketConstants.COPYRIGHT);
                   lResponse.put("license", JWebSocketConstants.LICENSE);
                 } else {
                   // if unknown type in this namespace, return corresponding error message
                   lResponse.put("code", -1);
                   lResponse.put("msg", "Token type '" + lType + "' not supported in namespace '" + lNS + "'.");
                 }
                 aEvent.sendToken(lResponse);
               }
           }

           public void processClosed(WebSocketEvent aEvent) {
             log.info("Client '" + aEvent.getSessionId() + "' disconnected.");
           }
       }
Chat




http://www.playframework.org/documentation/1.2.4/samples#aChata
ChatRoom room = ChatRoom.get(roomNo);

	   // Socket connected, join the chat room
	   EventStream<ChatRoom.Event> roomMessagesStream = room.join(user);

	   // Loop while the socket is open
	   while (inbound.isOpen()) {

	   	   // Wait for an event (either something coming on the inbound
	   	   // socket channel, or ChatRoom messages)
	   	   Either<WebSocketEvent, ChatRoom.Event> e = await(Promise
	   	   	    	   .waitEither(inbound.nextEvent(),
	   	   	    	   	    	   roomMessagesStream.nextEvent()));

	   	   // Case: User typed 'quit'
	   	   for (String userMessage : TextFrame.and(Equals("quit")).match(
	   	   	    	    e._1)) {
	   	   	    room.leave(user);
	   	   	    outbound.send("quit:ok");
	   	   	    disconnect();                                         // Case: Someone joined the room
	   	   }                                    	    	   	    	    for (ChatRoom.Join joined : ClassOf(ChatRoom.Join.class).match(
                                             	    	   	    	    	    	    e._2)) {
	   	   // Case: TextEvent received on the socket 	
                                             	        	    	    	    outbound.send("join:%s", joined.user);
	   	   for (String userMessage : TextFrame.match(e._1)) { 	
                                             	    	   	         }
	   	   	    room.say(user, userMessage);
	   	   }                                    	    	   	    	    // Case: New message on the chat room
                                             	    	   	    	    for (ChatRoom.Message message : ClassOf(ChatRoom.Message.class)
	   	                                        	    	   	    	    	    	    .match(e._2)) {
                                             	    	   	    	    	    outbound.send("message:%s:%s", message.user, message.text);
                                             	    	   	    	    }

                                             	    	   	    	    // Case: Someone left the room
                                             	    	   	    	    for (ChatRoom.Leave left : ClassOf(ChatRoom.Leave.class).match(
                                             	    	   	    	    	    	    e._2)) {
                                             	    	   	    	    	    outbound.send("leave:%s", left.user);
                                             	    	   	    	    }

                                             	    	   	    	    // Case: The socket has been closed
                                             	    	   	    	    for (WebSocketClose closed : SocketClosed.match(e._1)) {
                                             	    	   	    	    	    room.leave(user);
                                             	    	   	    	    	    disconnect();
                                             	    	   	    	    }

                                             	    	   	    }
Don’t Even...
• Nginx
 • Use HA Proxy / Varnish ahead of nginx
• Auto Manual STAY_ALIVE
• Combine REST & Websocket Servers
 • REST = Stateless
 • WebSockets = State-ful
Talk
Credits
•   Websocket.org

    •   http://www.websocket.org/

•   HTML5 Websocket API

    •   http://www.slideshare.net/ffdead/the-html5-websocket-api

    •   http://www.lewisbenge.net/index.php/2011/04/html-5-web-sockets-the-
        real-time-web/

•   Kaazing

    •   http://kaazing.com/

•   Play Framework

    •   http://www.playframework.org/documentation/1.2.4/home
Thank You

    www.artoo.in
sameersegal.github.com

Weitere ähnliche Inhalte

Was ist angesagt?

Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
The Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework EvolutionThe Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework EvolutionFITC
 
Google chrome presentation
Google chrome presentationGoogle chrome presentation
Google chrome presentationreza jalaluddin
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/smoret1979
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196Mahmoud Samir Fayed
 
Tornado web
Tornado webTornado web
Tornado webkurtiss
 
Serial Killers - or Deserialization for fun and profit
Serial Killers - or Deserialization for fun and profitSerial Killers - or Deserialization for fun and profit
Serial Killers - or Deserialization for fun and profitblaufish
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Sometimes web sockets_dont_work
Sometimes web sockets_dont_workSometimes web sockets_dont_work
Sometimes web sockets_dont_workXMPPUK
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Fwdays
 
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersFestGroup
 
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of code
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of codeSetup ephemeral password for TURN, Learn RTC in less than 200 Lines of code
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of codeAmitesh Madhur
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsersjeresig
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 

Was ist angesagt? (20)

Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
The Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework EvolutionThe Next Step in AS3 Framework Evolution
The Next Step in AS3 Framework Evolution
 
Google chrome presentation
Google chrome presentationGoogle chrome presentation
Google chrome presentation
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Couchdb w Ruby'm
Couchdb w Ruby'mCouchdb w Ruby'm
Couchdb w Ruby'm
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
Tornado web
Tornado webTornado web
Tornado web
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 
Serial Killers - or Deserialization for fun and profit
Serial Killers - or Deserialization for fun and profitSerial Killers - or Deserialization for fun and profit
Serial Killers - or Deserialization for fun and profit
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Sometimes web sockets_dont_work
Sometimes web sockets_dont_workSometimes web sockets_dont_work
Sometimes web sockets_dont_work
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
 
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
 
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of code
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of codeSetup ephemeral password for TURN, Learn RTC in less than 200 Lines of code
Setup ephemeral password for TURN, Learn RTC in less than 200 Lines of code
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Performance Improvements in Browsers
Performance Improvements in BrowsersPerformance Improvements in Browsers
Performance Improvements in Browsers
 
DDEV - Extended
DDEV - ExtendedDDEV - Extended
DDEV - Extended
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 

Ähnlich wie Websockets - DevFestX May 19, 2012

KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享Chia Wei Tsai
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioRick Copeland
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come backVladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come backDefconRussia
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126Go Tanaka
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSocketsJosh Glover
 
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."Dongwook Lee
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersViktor Gamov
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the ServerDavid Ruiz
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP ApisAdrian Cole
 

Ähnlich wie Websockets - DevFestX May 19, 2012 (20)

The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come backVladimir Vorontsov - Splitting, smuggling and cache poisoning come back
Vladimir Vorontsov - Splitting, smuggling and cache poisoning come back
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
T2 reading 20101126
T2 reading 20101126T2 reading 20101126
T2 reading 20101126
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
 
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."
IBM dwLive, "Internet & HTTP - 잃어버린 패킷을 찾아서..."
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
 

Kürzlich hochgeladen

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Kürzlich hochgeladen (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Websockets - DevFestX May 19, 2012

  • 1. Websockets Sameer Segal Artoo - Technology to the Rescue www.artoo.in
  • 4.
  • 5. KnockOut Tweety http://kot.artoo.in http://sameersegal.github.com/KnockOutTweety/
  • 9. HTTP // Request GET /home HTTP/1.1 Host: trial.artoo.in Connection: keep-alive Cache-Control: max-age=0 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: ....... // Response HTTP/1.1 200 OK Date: Sat, 19 May 2012 06:04:24 GMT Server: Play! Framework;master-jenkins-Artoo-Play-15;prod Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Set-Cookie: ..... . . . Via: 1.1 artoo.in Vary: Accept-Encoding Content-Encoding: gzip Connection: close Transfer-Encoding: chunked
  • 10. Websocket // Request GET wss://socket.artoo.in/chat? username=admin&clientId=0782cd45-307d-414b-8efa-b2156253b6xx HTTP/1.1 Origin: https://trial.artoo.in Cookie: ... __utma=27942636.1788801618.1323048033.1337320289.1337406233.265; __utmb=27942636.7.10.1337406233; __utmc=27942636; __utmz=27942636.1337136927.261.12.utmcsr=google|utmccn=(organic)| utmcmd=organic|utmctr=(not%20provided) Connection: Upgrade Sec-WebSocket-Extensions: x-webkit-deflate-frame Host: socket.artoo.in Sec-WebSocket-Key: ego8R97Ruc3d5RPwRhhtzw== Upgrade: websocket Sec-WebSocket-Version: 13 // Resonse HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: websocket Sec-WebSocket-Accept: CEbdJJgOTp1ZCcx6+RZTngrI5Ek=
  • 11. HTTP Websocket GET wss://socket.artoo.in/chat? GET /home HTTP/1.1 username=admin&clientId=0782cd45-307d-414b-8efa-b2156253b6xx Host: trial.artoo.in HTTP/1.1 Connection: keep-alive Origin: https://trial.artoo.in Cache-Control: max-age=0 Cookie: ... User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) __utma=27942636.1788801618.1323048033.1337320289.1337406233.26 AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 5; __utmb=27942636.7.10.1337406233; __utmc=27942636; Safari/536.5 __utmz=27942636.1337136927.261.12.utmcsr=google| Accept: text/html,application/xhtml+xml,application/ utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided) xml;q=0.9,*/*;q=0.8 Connection: Upgrade Accept-Encoding: gzip,deflate,sdch Sec-WebSocket-Extensions: x-webkit-deflate-frame Accept-Language: en-US,en;q=0.8 Host: socket.artoo.in Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Sec-WebSocket-Key: ego8R97Ruc3d5RPwRhhtzw== Cookie: ....... Upgrade: websocket Sec-WebSocket-Version: 13 HTTP/1.1 200 OK Date: Sat, 19 May 2012 06:04:24 GMT Server: Play! Framework;master-jenkins-Artoo-Play-15;prod Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Set-Cookie: ..... HTTP/1.1 101 Switching Protocols . Connection: Upgrade . Upgrade: websocket . Sec-WebSocket-Accept: CEbdJJgOTp1ZCcx6+RZTngrI5Ek= Via: 1.1 artoo.in Vary: Accept-Encoding Content-Encoding: gzip Connection: close Transfer-Encoding: chunked One time Everytime (2 bytes of overhead for every message)
  • 12. "Reducing kilobytes of data to 2 bytes…and reducing latency from 150ms to 50ms is far more than marginal. In fact, these two factors alone are enough to make Web Sockets seriously interesting to Google." - Ian Hickson (Google’s HTML5 Spec Lead)
  • 13. Specs • Based on TCP but not true TCP socket • ws:// or wss:// • Full-Duplex • Both UTF-8 strings and binary frame can be sent in any direction • More at http://dev.w3.org/html5/ websockets/
  • 14. Use?
  • 15. JS Regular Javascript Client-Side var socket = null; var socketUrl = “ws://localhost:8080/feed”; $(function(){ socket = new WebSocket(socketUrl); socket.onopen = function(event) { } socket.onmessage = function(event) { } socket.onclose = function(event) { } });
  • 16. JS jquery-websocket http://code.google.com/p/jquery-websocket/ Client-Side
  • 17. Android Java Websocket https://github.com/TooTallNate/Java-WebSocket Client-Side @Override public class SampleSocket extends WebSocketClient { public void onMessage(String message) { Chat chat = Chat.fromJSON(message); private Context context; private boolean connected = false; if (chat != null) { private Handler h = new Handler(); ContentValues values = new ContentValues(); private Runnable r = new Runnable() { switch (chat.event) { @Override case ONLINE: public void run() { try { break; Chat chat = new Chat(); case OFFLINE: chat.event = event_type.STAY_ALIVE; if (connected) { break; send(chat.toJSON()); case USER: } } catch (IOException e) { break; e.printStackTrace(); case MESSAGE: } break; h.postDelayed(r, 10000); default: } }; } public SampleSocket(Context context, URI serverUri) { // Insert / Update into DB super(serverUri); } this.context = context; } // Sending keep alive messages h.postDelayed(r, 5000); @Override } public void onOpen() { public SampleSocket(Context context, URI serverUri, } WebSocketDraft draft) { super(serverUri, draft); @Override this.context = context; public void onClose() { } } @Override public void onIOError(IOException ex) { }
  • 18. Android Client-Side Activity 1 Use Messenger Service Activity 2 WebSocket
  • 19. Java jquery-websocket http://jwebsocket.org/ Server-Side public class JWebSocketTokenListenerSample implements WebSocketTokenListener { private static Logger log = Logging.getLogger(JWebSocketTokenListenerSample.class); public void processOpened(WebSocketEvent aEvent) { log.info("Client '" + aEvent.getSessionId() + "' connected."); } public void processPacket(WebSocketEvent aEvent, WebSocketPacket aPacket) { // here you can process any non-token low level message, if desired } public void processToken(WebSocketTokenEvent aEvent, Token aToken) { log.info("Client '" + aEvent.getSessionId() + "' sent Token: '" + aToken.toString() + "'."); // here you can interpret the token type sent from the client according to your needs. String lNS = aToken.getNS(); String lType = aToken.getType(); // check if token has a type and a matching namespace if (lType != null && "my.namespace".equals(lNS)) { // create a response token Token lResponse = aEvent.createResponse(aToken); if ("getInfo".equals(lType)) { // if type is "getInfo" return some server information lResponse.put("vendor", JWebSocketConstants.VENDOR); lResponse.put("version", JWebSocketConstants.VERSION_STR); lResponse.put("copyright", JWebSocketConstants.COPYRIGHT); lResponse.put("license", JWebSocketConstants.LICENSE); } else { // if unknown type in this namespace, return corresponding error message lResponse.put("code", -1); lResponse.put("msg", "Token type '" + lType + "' not supported in namespace '" + lNS + "'."); } aEvent.sendToken(lResponse); } } public void processClosed(WebSocketEvent aEvent) { log.info("Client '" + aEvent.getSessionId() + "' disconnected."); } }
  • 21. ChatRoom room = ChatRoom.get(roomNo); // Socket connected, join the chat room EventStream<ChatRoom.Event> roomMessagesStream = room.join(user); // Loop while the socket is open while (inbound.isOpen()) { // Wait for an event (either something coming on the inbound // socket channel, or ChatRoom messages) Either<WebSocketEvent, ChatRoom.Event> e = await(Promise .waitEither(inbound.nextEvent(), roomMessagesStream.nextEvent())); // Case: User typed 'quit' for (String userMessage : TextFrame.and(Equals("quit")).match( e._1)) { room.leave(user); outbound.send("quit:ok"); disconnect(); // Case: Someone joined the room } for (ChatRoom.Join joined : ClassOf(ChatRoom.Join.class).match( e._2)) { // Case: TextEvent received on the socket outbound.send("join:%s", joined.user); for (String userMessage : TextFrame.match(e._1)) { } room.say(user, userMessage); } // Case: New message on the chat room for (ChatRoom.Message message : ClassOf(ChatRoom.Message.class) .match(e._2)) { outbound.send("message:%s:%s", message.user, message.text); } // Case: Someone left the room for (ChatRoom.Leave left : ClassOf(ChatRoom.Leave.class).match( e._2)) { outbound.send("leave:%s", left.user); } // Case: The socket has been closed for (WebSocketClose closed : SocketClosed.match(e._1)) { room.leave(user); disconnect(); } }
  • 22. Don’t Even... • Nginx • Use HA Proxy / Varnish ahead of nginx • Auto Manual STAY_ALIVE • Combine REST & Websocket Servers • REST = Stateless • WebSockets = State-ful
  • 23. Talk
  • 24. Credits • Websocket.org • http://www.websocket.org/ • HTML5 Websocket API • http://www.slideshare.net/ffdead/the-html5-websocket-api • http://www.lewisbenge.net/index.php/2011/04/html-5-web-sockets-the- real-time-web/ • Kaazing • http://kaazing.com/ • Play Framework • http://www.playframework.org/documentation/1.2.4/home
  • 25. Thank You www.artoo.in sameersegal.github.com

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n