SlideShare a Scribd company logo
Real-Time Web:  Gevent and Socket.io Rick Copeland @rick446 [email_address]
Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
A (very) Brief Survey of Python Asynchronous Programming AsynCore In stdlib, used for stdlib SMTP server Nobody cares about it anymore   Twisted Large community, vast amounts of code Callbacks hurt my brain Stackless Cool, cooperative multithreading Needs a custom Python Event-based green threads Like stackless, but in regular Python Know when you yield
Let’s Go Green:  Async that Doesn’t Hurt Your Brain Greenlets: Cooperative, lightweight threads Very forgiving – mutexes rarely needed Use it for IO!

Recommended for you

Modern Perl
Modern PerlModern Perl
Modern Perl

A brief introduction to modern Perl programming tools that I gave at the OpenTech conference in Spetember 2010.

opentechperlmodern perl
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging

The document discusses asynchronous programming in PHP using non-blocking I/O and event loops. It covers using asynchronous techniques like ReactPHP to scrape web pages concurrently without blocking. Promises and streams are also discussed as ways to handle asynchronous operations and pass data between components. Finally, messaging techniques like websockets and WAMP are presented as ways to build real-time applications.

html5ratchetreactphp
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons

The document describes a project to build a website called PerkyProfiler that retrieves user profile information from different services like GitHub, Flickr, and Twitter by taking URLs as input. It will use Perl and several Perl modules. The project will be built using the Catalyst web framework and Moose/MooseX for object-oriented programming. It describes using Moose roles, custom types, declarative class definitions, and functional programming techniques in Perl. The goal is to generate a unified user profile by combining data from different services for a given URL.

perlmodern perlcatalyst
Gevent: Greenlets Spawn helpers spawn(my_python_function, *args, **kwargs) Also spawn_later(), spawn_link(), etc. Greenlet class Like threads but cooperative Useful properties: .get(), .join(), .kill(), .link() Timeouts Timeout(seconds, exception).start() Pools: for limiting concurrency, use Pool.spawn
Gevent: Communication Event set()  clear() wait() Queue Modeled after Queue.Queue .get() .put() __iter__() PriorityQueue, LifoQueue, JoinableQueue
Gevent: Networking “ Green” versions of sockets, select(), ssl, and dns Quick and dirty: import   gevent.monkey gevent .monkey.patch_all()
Gevent: Servers Simple callback interface Creates one greenlet per connection (but remember, that’s OK!) def   handle(socket, address): print   'new connection!’ server  = StreamServer( ( '127.0.0.1',  1234), handle) # creates a new server server .start() # start accepting new connections

Recommended for you

Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.

This document discusses using an HTTP proxy to load specific web pages for testing purposes. It explains that many web pages contain resources from multiple domains that cannot be saved locally. An HTTP proxy can be used to intercept requests and redirect local URLs to a test server, while passing through external URLs to the actual web server. The document provides code examples for setting up an HTTP proxy using HTTP::Proxy and modifying the LWP user agent to handle local and remote URLs differently. Using this approach allows a test loop to load repeatable web page content from both local and external sources.

perl web proxy object repeatable testing
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl

Why is blocking IO so bad? Why is non-blocking code with callbacks so bad? Here are a few ways to deal with both problems in Perl.

non-blockinganyeventmojolicious
Presentation of JSConf.eu
Presentation of JSConf.euPresentation of JSConf.eu
Presentation of JSConf.eu

I went to JSConf.eu 2009 and was asked to present a "summary" of my take aways from the conference at Gothenburg DotnetForum in December 2009.

dotnetforumjsconf
Gevent: WSGI gevent.wsgi Fast  (~4k requests/s) No streaming, pipelining, or ssl   gevent.pywsgi:  Full featured Slower (“only” 3k requests/s) from   gevent  import  pywsgi def   hello_world(env, start_response): start_response( '200 OK', [('Content-Type', 'text/html')]) yield   '<b>Hello world</b>’ server  = pywsgi.WSGIServer( ( '0.0.0.0',  8080), hello_world) server .serve_forever()
Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
What is the real-time web? No page refreshes Server push Examples: chat, realtime analytics, … Implementation Flash (eww…) Polling (2x eww…) Long polling (wow – that’s clever :-/ ) HTML5 WebSockets ( Super-easy! Awesome!  Security vulnerabilities! Immature spec! )
SocketIO to the Rescue “ Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms.”

Recommended for you

Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf

The document discusses using Node.js to build streaming services. It describes how Node.js allows for scalable server-side code using JavaScript and mentions libraries like JSONStream that can be used to parse JSON streams. The document also discusses different types of streaming like simplex, throughput, and duplex streaming and how to manage backpressure in streams.

node.jsnodenodejs
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault

Static typing in Vault refers to enforcing the structure and location of secrets stored in Vault. This can be achieved by using a script or tool to validate secrets against JSON schemas before they are written or accessed. The schemas define the required properties and structure for different secret types. Using a generic validation tool allows schemas to be centrally defined and ensures secrets match the expected format, reducing errors from incorrectly structured secrets.

Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy

Small Node.js proxy to turn a paginated JSON REST API into a CSV streaming download. Examples of code and patterns. Presented at the London Node User Group meetup, April 2014

javascriptservercode
Socket.io Example <script  src=&quot;/socket.io/socket.io.js&quot; ></script> <script> var  socket  = io.connect( 'http://localhost'); socket.on('news',  function  (data) { console.log(data); socket.emit( 'my other event’, { my : 'data' }); }); </script>
gevent_socketio def   hello_world(environ, start_response): if   not  environ[ 'PATH_INFO'] .startswith( '/socket.io'): return  serve_file(environ, start_response) socketio  = environ[ 'socketio'] while  True: socketio .send( 'Hello, world') gevent .sleep( 2)
Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
ZeroMQ Overview C library with Python bindings ZMQ “sockets” are message based, delivery is via a dedicated communication thread ZMQ transports (tcp, inproc, unix, multicast) ZMQ socket types REQ/RES PUSH/PULL PUB/SUB …

Recommended for you

Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco

DBIx::MoCo is an ORM for MySQL and SQLite that provides easy SQL operations and Ruby-like list methods for retrieving and manipulating data. It supports features like caching, relationships between models, and transparent type inflation. Tests can be written using fixtures that load sample data from YAML files. While it aims to be simple and fast, its documentation is limited and some bugs may exist.

Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009

- PSGI (Perl Web Server Gateway Interface) and Plack provide a common interface and utilities for building web applications and servers in Perl. - PSGI defines a standard interface that web frameworks can implement to work with different server implementations. Plack provides server implementations like standalone, FastCGI and Apache modules. - This allows frameworks to focus on the application code instead of server specifics, and servers to handle multiple frameworks. Common middleware and testing utilities are also included. - Examples of frameworks that have adopted PSGI include Catalyst, Maypole and Mojolicious. Popular servers built on Plack include Starman and Dancer.

루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날

The document discusses Concurrency-oriented Programming (COP) using Erlang. It explains how Erlang programs work using lightweight processes that communicate asynchronously via message passing. This allows for high performance, reliability, and scalability. It provides examples of stateless server processes and using CouchDB for schema-free document storage accessible via REST APIs. Ruby libraries for interacting with CouchDB are also mentioned.

pyzmq and gevent_zmq pyzmq works great for threading gevent_zmq is necessary for gevent (single-threaded) Be careful when forking or otherwise using multiprocessing! Gevent has a global “hub” of greenlets ZeroMQ has a global thread & “context” for communication Best to wait till done forking before initializing ZeroMQ
ZeroMQ: bind/connect and pub/sub from   gevent_zeromq   import  zmq context  = zmq.Context() sock_queue = context.socket(zmq.PUB) sock_queue.bind( 'inproc://chat') zmq_sock  = context.socket(zmq.SUB) zmq_sock.setsockopt(zmq.SUBSCRIBE,  &quot;&quot;) zmq_sock .connect( 'inproc://chat')
Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
WebChat: Design Incoming Greenlet ZMQ send Outgoing Greenlet Socket.io ZMQ recv JSON Messages JSON Messages Socket.io

Recommended for you

A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web

This document discusses the evolution of web development in Perl, from CGI scripts to modern PSGI-based frameworks. It introduces PSGI as an interface between web applications and web servers, and Plack as a toolkit for building PSGI applications and middleware. The document outlines many PSGI web servers and frameworks that can be used to build and deploy Perl web applications according to the PSGI standard.

plackperlpsgi
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops

This document discusses event loops and how they work. Event loops allow non-blocking operations by listening for events like network data or user input in parallel. They achieve this through callbacks, select(), threads, or other asynchronous programming techniques. Common examples of event loops include browser JavaScript, game engines, servers, and other applications that perform non-blocking IO operations. Event loops can be complex to work with correctly due to issues like race conditions, so abstractions like promises are recommended.

event loopnon-blocking
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher

Pushing symfony events in real time to your clients This talk, held at the symfony live Paris unconference, gives an overview about how events thrown in symfony can be dispatched in real time to web clients. It describes the architecture of the solution and provides examples using the open source comet server APE

apeajaxevents
WebChat: HTML <h1> Socket.io Chatterbox </h1> <div   id=&quot;status&quot; style=&quot;border:1px solid black;&quot; > Disconnected </div> <form> <input   id=&quot;input&quot; style=&quot;width: 35em;&quot; > </form> <div   id=&quot;data&quot; style=&quot;border:1px solid black;&quot; > </div> <script  src=&quot;/js/jquery.min.js&quot; ></script> <script  src=&quot;/js/socket.io.js&quot; ></script> <script  src=&quot;/js/test.js&quot; ></script>
WebChat: Javascript Setup ( function () { // Create and connect socket var  socket  =  new  io.Socket( 'localhost'); socket.connect(); // Socket status var  $status  = $( '#status'); socket.on('connect',  function () { $status.html( '<b>Connected: '  + socket.transport.type +  '</b>'); }); socket.on('error',  function () { $status.html( '<b>Error</b>'); }); socket.on('disconnect',  function () { $status.html( '<b>Closed</b>'); });
WebChat: Javascript Communication // Send data to the server var  $form  = $( 'form'); var  $input  = $( '#input'); $form.bind('submit',  function () { socket.send($input.val()); $input.val( ''); return   false ; }); // Get data back from the server var  $data  = $( '#data'); socket.on('message',  function (msg) { msg  = $.parseJSON(msg) ; var  u  = msg.u ||  'SYSTEM’; $data.prepend($( '<em>'  + u +  '</em>:  '  + msg.m +  '<br/>')); }); })();
WebChat: Server def   chat(environ, start_response): if   not  environ[ 'PATH_INFO'] .startswith( '/socket.io): return  serve_file(environ, start_response) socketio  = environ[ 'socketio'] #... handle auth ... zmq_sock  = context.socket(zmq.SUB) zmq_sock.setsockopt(zmq.SUBSCRIBE,  &quot;&quot;) zmq_sock .connect( 'inproc://chat') greenlets  = [ gevent.spawn(incoming, uname, socketio), gevent.spawn(outgoing, zmq_sock, socketio) ] gevent .joinall(greenlets)

Recommended for you

WebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossibleWebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossible

How to make web socket daemons with PHP. Also in this talk we'll look at some similar topics like MQs

websocketsratchetzeromq
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul Connect

Things like Infrastructure as Code, Service Discovery and Config Management can and have helped us to quickly build and rebuild infrastructure but we haven't nearly spend enough time to train our self to review, monitor and respond to outages. Does our platform degrade in a graceful way or what does a high cpu load really mean? What can we learn from level 1 outages to be able to run our platforms more reliably. We all love infrastructure as code, we automate everything ™. However making sure all of our infrastructure assets are monitored effectively can be slow and resource intensive multi stage process. During this talk we will investigate how we can setup and observe a service mesh platform using HashiCorp's Consul Connect by recording its metrics. logs and traces. This talk will focus on configuring and analysing the metrics, logs and traces Consul Connect produces using Prometheus, Loki, Tempo and Grafana.

consulenvoyprometheus
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP

This talk was given at the Dutch PHP Conference 2011 and details the use of Comet (aka reverse ajax or ajax push) technologies and the importance of websockets and server-sent events. More information is available at http://joind.in/3237.

king foodpc11php
WebChat: Greenlets def   incoming(uname, socketio): while  True: for  part  in  socketio .recv(): sock_queue.send(json.dumps( dict( u =uname, m=part))) def   outgoing(zmq_sock, socketio): while  True: socketio.send(zmq_sock.recv())
Get the Code! Socket.io http://socket.io MIT License Chatterbox http://sf.net/u/rick446/pygotham Apache License ZeroMQ http://www.zeromq.org LGPL License Gevent http://gevent.org MIT License
Rick Copeland @rick446 [email_address]

More Related Content

What's hot

AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
clkao
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
Masahiro Nagano
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
Perl Careers
 
Modern Perl
Modern PerlModern Perl
Modern Perl
Dave Cross
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
Steve Rhoades
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
Matt Follett
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
deepfountainconsulting
 
Presentation of JSConf.eu
Presentation of JSConf.euPresentation of JSConf.eu
Presentation of JSConf.eu
Fredrik Wendt
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
GlynnForrest
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
Ismael Celis
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
Naoya Ito
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
Tatsuhiko Miyagawa
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
Sukjoon Kim
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
Wallace Reis
 
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
deepfountainconsulting
 
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher
Peter Dietrich
 
WebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossibleWebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossible
Yoan-Alexander Grigorov
 
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul Connect
Bram Vogelaar
 

What's hot (20)

AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
Presentation of JSConf.eu
Presentation of JSConf.euPresentation of JSConf.eu
Presentation of JSConf.eu
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날루비가 얼랭에 빠진 날
루비가 얼랭에 빠진 날
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
 
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher
 
WebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossibleWebSockets with PHP: Mission impossible
WebSockets with PHP: Mission impossible
 
Observability with Consul Connect
Observability with Consul ConnectObservability with Consul Connect
Observability with Consul Connect
 

Similar to Real-Time Python Web: Gevent and Socket.io

Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
David Lindkvist
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
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
Aarti Parikh
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
Aman Kohli
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
Tatsuhiko Miyagawa
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
Node.js
Node.jsNode.js
Node.js
hotrannam
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
Dongmin Yu
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
GWTcon
 
PSGI/Plack OSDC.TW
PSGI/Plack OSDC.TWPSGI/Plack OSDC.TW
PSGI/Plack OSDC.TW
Tatsuhiko Miyagawa
 
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
Frank Lyaruu
 
Fast SOA with Apache Synapse
Fast SOA with Apache SynapseFast SOA with Apache Synapse
Fast SOA with Apache Synapse
Paul Fremantle
 
About Node.js
About Node.jsAbout Node.js
About Node.js
Artemisa Yescas Engler
 
swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClient
Shinya Mochida
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
Sameer Segal
 

Similar to Real-Time Python Web: Gevent and Socket.io (20)

Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and 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
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Node.js
Node.jsNode.js
Node.js
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
PSGI/Plack OSDC.TW
PSGI/Plack OSDC.TWPSGI/Plack OSDC.TW
PSGI/Plack OSDC.TW
 
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
 
Fast SOA with Apache Synapse
Fast SOA with Apache SynapseFast SOA with Apache Synapse
Fast SOA with Apache Synapse
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClient
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
 

More from Rick Copeland

Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Schema Design at Scale
Schema Design at ScaleSchema Design at Scale
Schema Design at Scale
Rick Copeland
 
Building Your First MongoDB Application
Building Your First MongoDB ApplicationBuilding Your First MongoDB Application
Building Your First MongoDB Application
Rick Copeland
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and Pyramid
Rick Copeland
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
Rick Copeland
 
Chef on Python and MongoDB
Chef on Python and MongoDBChef on Python and MongoDB
Chef on Python and MongoDB
Rick Copeland
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rick Copeland
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForgeAllura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Rick Copeland
 
MongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDBMongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDB
Rick Copeland
 

More from Rick Copeland (11)

Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Schema Design at Scale
Schema Design at ScaleSchema Design at Scale
Schema Design at Scale
 
Building Your First MongoDB Application
Building Your First MongoDB ApplicationBuilding Your First MongoDB Application
Building Your First MongoDB Application
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and Pyramid
 
Scaling with MongoDB
Scaling with MongoDBScaling with MongoDB
Scaling with MongoDB
 
Chef on Python and MongoDB
Chef on Python and MongoDBChef on Python and MongoDB
Chef on Python and MongoDB
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and MingRapid and Scalable Development with MongoDB, PyMongo, and Ming
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
 
Allura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForgeAllura - an Open Source MongoDB Based Document Oriented SourceForge
Allura - an Open Source MongoDB Based Document Oriented SourceForge
 
MongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDBMongoATL: How Sourceforge is Using MongoDB
MongoATL: How Sourceforge is Using MongoDB
 

Recently uploaded

Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 

Recently uploaded (20)

Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 

Real-Time Python Web: Gevent and Socket.io

  • 1. Real-Time Web: Gevent and Socket.io Rick Copeland @rick446 [email_address]
  • 2. Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
  • 3. A (very) Brief Survey of Python Asynchronous Programming AsynCore In stdlib, used for stdlib SMTP server Nobody cares about it anymore  Twisted Large community, vast amounts of code Callbacks hurt my brain Stackless Cool, cooperative multithreading Needs a custom Python Event-based green threads Like stackless, but in regular Python Know when you yield
  • 4. Let’s Go Green: Async that Doesn’t Hurt Your Brain Greenlets: Cooperative, lightweight threads Very forgiving – mutexes rarely needed Use it for IO!
  • 5. Gevent: Greenlets Spawn helpers spawn(my_python_function, *args, **kwargs) Also spawn_later(), spawn_link(), etc. Greenlet class Like threads but cooperative Useful properties: .get(), .join(), .kill(), .link() Timeouts Timeout(seconds, exception).start() Pools: for limiting concurrency, use Pool.spawn
  • 6. Gevent: Communication Event set() clear() wait() Queue Modeled after Queue.Queue .get() .put() __iter__() PriorityQueue, LifoQueue, JoinableQueue
  • 7. Gevent: Networking “ Green” versions of sockets, select(), ssl, and dns Quick and dirty: import gevent.monkey gevent .monkey.patch_all()
  • 8. Gevent: Servers Simple callback interface Creates one greenlet per connection (but remember, that’s OK!) def handle(socket, address): print 'new connection!’ server = StreamServer( ( '127.0.0.1', 1234), handle) # creates a new server server .start() # start accepting new connections
  • 9. Gevent: WSGI gevent.wsgi Fast (~4k requests/s) No streaming, pipelining, or ssl  gevent.pywsgi: Full featured Slower (“only” 3k requests/s) from gevent import pywsgi def hello_world(env, start_response): start_response( '200 OK', [('Content-Type', 'text/html')]) yield '<b>Hello world</b>’ server = pywsgi.WSGIServer( ( '0.0.0.0', 8080), hello_world) server .serve_forever()
  • 10. Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
  • 11. What is the real-time web? No page refreshes Server push Examples: chat, realtime analytics, … Implementation Flash (eww…) Polling (2x eww…) Long polling (wow – that’s clever :-/ ) HTML5 WebSockets ( Super-easy! Awesome! Security vulnerabilities! Immature spec! )
  • 12. SocketIO to the Rescue “ Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms.”
  • 13. Socket.io Example <script src=&quot;/socket.io/socket.io.js&quot; ></script> <script> var socket = io.connect( 'http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit( 'my other event’, { my : 'data' }); }); </script>
  • 14. gevent_socketio def hello_world(environ, start_response): if not environ[ 'PATH_INFO'] .startswith( '/socket.io'): return serve_file(environ, start_response) socketio = environ[ 'socketio'] while True: socketio .send( 'Hello, world') gevent .sleep( 2)
  • 15. Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
  • 16. ZeroMQ Overview C library with Python bindings ZMQ “sockets” are message based, delivery is via a dedicated communication thread ZMQ transports (tcp, inproc, unix, multicast) ZMQ socket types REQ/RES PUSH/PULL PUB/SUB …
  • 17. pyzmq and gevent_zmq pyzmq works great for threading gevent_zmq is necessary for gevent (single-threaded) Be careful when forking or otherwise using multiprocessing! Gevent has a global “hub” of greenlets ZeroMQ has a global thread & “context” for communication Best to wait till done forking before initializing ZeroMQ
  • 18. ZeroMQ: bind/connect and pub/sub from gevent_zeromq import zmq context = zmq.Context() sock_queue = context.socket(zmq.PUB) sock_queue.bind( 'inproc://chat') zmq_sock = context.socket(zmq.SUB) zmq_sock.setsockopt(zmq.SUBSCRIBE, &quot;&quot;) zmq_sock .connect( 'inproc://chat')
  • 19. Getting started with Gevent AJAX, push, WebSockets, wha? ZeroMQ for fun and multiprocessing Putting it all together
  • 20. WebChat: Design Incoming Greenlet ZMQ send Outgoing Greenlet Socket.io ZMQ recv JSON Messages JSON Messages Socket.io
  • 21. WebChat: HTML <h1> Socket.io Chatterbox </h1> <div id=&quot;status&quot; style=&quot;border:1px solid black;&quot; > Disconnected </div> <form> <input id=&quot;input&quot; style=&quot;width: 35em;&quot; > </form> <div id=&quot;data&quot; style=&quot;border:1px solid black;&quot; > </div> <script src=&quot;/js/jquery.min.js&quot; ></script> <script src=&quot;/js/socket.io.js&quot; ></script> <script src=&quot;/js/test.js&quot; ></script>
  • 22. WebChat: Javascript Setup ( function () { // Create and connect socket var socket = new io.Socket( 'localhost'); socket.connect(); // Socket status var $status = $( '#status'); socket.on('connect', function () { $status.html( '<b>Connected: ' + socket.transport.type + '</b>'); }); socket.on('error', function () { $status.html( '<b>Error</b>'); }); socket.on('disconnect', function () { $status.html( '<b>Closed</b>'); });
  • 23. WebChat: Javascript Communication // Send data to the server var $form = $( 'form'); var $input = $( '#input'); $form.bind('submit', function () { socket.send($input.val()); $input.val( ''); return false ; }); // Get data back from the server var $data = $( '#data'); socket.on('message', function (msg) { msg = $.parseJSON(msg) ; var u = msg.u || 'SYSTEM’; $data.prepend($( '<em>' + u + '</em>: ' + msg.m + '<br/>')); }); })();
  • 24. WebChat: Server def chat(environ, start_response): if not environ[ 'PATH_INFO'] .startswith( '/socket.io): return serve_file(environ, start_response) socketio = environ[ 'socketio'] #... handle auth ... zmq_sock = context.socket(zmq.SUB) zmq_sock.setsockopt(zmq.SUBSCRIBE, &quot;&quot;) zmq_sock .connect( 'inproc://chat') greenlets = [ gevent.spawn(incoming, uname, socketio), gevent.spawn(outgoing, zmq_sock, socketio) ] gevent .joinall(greenlets)
  • 25. WebChat: Greenlets def incoming(uname, socketio): while True: for part in socketio .recv(): sock_queue.send(json.dumps( dict( u =uname, m=part))) def outgoing(zmq_sock, socketio): while True: socketio.send(zmq_sock.recv())
  • 26. Get the Code! Socket.io http://socket.io MIT License Chatterbox http://sf.net/u/rick446/pygotham Apache License ZeroMQ http://www.zeromq.org LGPL License Gevent http://gevent.org MIT License
  • 27. Rick Copeland @rick446 [email_address]