Fork me on GitHub

WebSockets

A WebSocket is a standard protocol for two-way communication between servers and clients. The WebSockets protocol does not run over HTTP, instead it is a separate implementation on top of TCP.

Why use WebSockets?

WebSockets allow two-way communication between the client and server. A WebSockets-enabled application allows a web server to push data to a web browser without the browser having to poll for updates via HTTP. Allowing push from the server to the client and vice versa is much more efficient than having the client constantly ask the server "are there any updates?".

Previous approaches for for keeping a connection alive between client and server over HTTP, such as [Comet](http://en.wikipedia.org/wiki/Comet_(programming), have either used long polling or were not implemented by all browsers.

JavaScript client libraries

  • Socket.io's client side JavaScript library can be used to connect to a server side WebSockets implementation.

  • web-socket-js is a Flash-based client-side WebSockets implementation.

Websockets with Nginx

Nginx officially supports WebSocket proxying as of version 1.3. However, you have to configure the Upgrade and Connection headers to ensure requests are passed through Nginx to your WSGI server. It can be tricky to set this up the first time. The following resources are helpful for setting up the configuration properly.

General WebSockets resources

Python-specific WebSockets resources

  • Real-time in Python provides Python-specific context for how the server push updates were implemented in the past and how Python's tools have evolved to perform server side updates.

  • The Choose Your Own Adventure Presentations tutorial uses WebSockets via gevent on the server and socketio.js for pushing vote count updates from the server to the client.

  • Async with Bottle shows how to use greenlets to support WebSockets with the Bottle web framework.

  • If you're deploying to Heroku, there is a specific WebSockets guide for getting your Python application up and running.

What's next for your web application after setting up WebSockets?

How do I execute Python since the web server doesn't do that?

How should I install Python libraries on the server?

What should I use to code my Python application?


Interested in a complete Full Stack Python book with detailed tutorials and example code? Sign up here and you'll get an alert email if a book is created. No other emails will be sent other than sign up confirmation.