Bartosz Zaczyński (Grand Parade Poland) - WebSocket for Dummies

  • View
    191

  • Download
    3

  • Category

    Mobile

Preview:

Citation preview

WebSocket for Dummies

Bartosz Zaczyńskibartosz.zaczynski@grandparade.co.uk

TCP/IP Socket

http://www.freeimages.co.uk/

Protocol

http://www.freeimages.co.uk/

Protocol: telnet

Protocol: HTTP

Protocol: HTTPS

Protocol: fixed length message

Protocol: message delimiter

Example: Betradar TCP/SSL

@tornado.gen.coroutinedef receive(self): """Read CRLF-delimited messages and push them onto the queue.""" try: if not self.iostream.closed():

message_body = yield self.iostream.read_until('\r\n\r\n')

logger.debug('Received message: %s', message_body.strip())

received_at = datetime.datetime.utcnow() message = parser.parse(message_body, received_at)

if message is not None: if self.is_whitelisted(message): self.messages.enqueue(message) self.log(message)

self.ioloop.add_callback(self.receive)

except tornado.iostream.StreamClosedError:

if not self._closing: logger.error('Betradar connection closed by remote endpoint')

self.heartbeat.stop()

if self.on_closed: self.on_closed()

WebSocket: handshake

WebSocket: server frame

WebSocket: client frame

WebSocket: JavaScript API

<!DOCTYPE html><html><head> <title>WebSocket Demo</title> <script> var ws = new WebSocket("ws://localhost:8080/websocket");

ws.onopen = function(event) { console.log("open"); }; ws.onclose = function(event) { console.log("closed"); }; ws.onerror = function(event) { console.log("error"); }; ws.onmessage = function(event) { console.log(event.data); };

function onButtonClick() { ws.send(document.getElementById("message").value) } </script></head><body> <input type="text" id="message"> <button type="button" onclick="onButtonClick();">Send</button></body></html>

WebSocket: JavaScript libs

var ws = STOMP.over(new SockJS("/websocket"));

var ws = io.connect("http://localhost:8080/websocket");

UNSUBSCRIBE

id:sub-0

\u0000

SUBSCRIBEid:sub-0destination:/topic/chat.all\u0000

WebSocket: sub protocol

CONNEC

T

accept

-versi

on:1.1

,1.0

heart-

beat:1

0000,1

0000

\u0000

CONNECTEDversion:1.1heart-beat:0,0\u0000

MESSAGEsubscription:sub-0message-id:007destination:/topic/chat.allcontent-type:text/plaincontent-length:11

hello world\u0000

SENDdestination:/topic/chat.all

content-type:text/plainhello world\u0000

Debugging

Summary

1. Lightweight binary protocol on top of TCP.

2. Different from HTTP (except for the handshake).

3. Replaces AJAX polling and plug­ins such as Flash.

Q&A

Bartosz Zaczyńskibartosz.zaczynski@grandparade.co.uk

Recommended