Sending images over websockets in Python 2.7

Below you’ll find an example of a Python WebSocket client that receives and shows a image that it gets from a Python WebSocket server.

The example is quite simple, and is just an example of how you could send a image over a WebSocket connection.

The reason why I chose WebSockets over a regular TCP/IP connection is that it requires less code ūüôā

You’ll need to install the¬†Tornado¬†module to get the server working, and the¬†websocket-client¬†module to get the client running

Server code:

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import base64
class WebSocketHandler(tornado.websocket.WebSocketHandler):
	def initialize(self):
		with open("some_image.png", "rb") as imageFile:
			self.str = base64.b64encode(
	def open(self):
		print 'new connection'
	def on_message(self, message):
		print message
	def on_close(self):
		print 'connection closed'
if __name__ == '__main__':
	application = tornado.web.Application([
	(r'/ws', WebSocketHandler),
	http_server = tornado.httpserver.HTTPServer(application)

Client code:

from PIL import Image
import websocket
import cStringIO
import base64

class WSClient():

	def __init__(self):
		websocket.enableTrace(False) = websocket.WebSocketApp("ws://",
		on_message = self.on_message,
		on_error = self.on_error,
		on_close = self.on_close) = self.on_open

	def on_message(self, ws, message):
		image_string = cStringIO.StringIO(base64.b64decode(message))
		image =

	def on_error(self, ws, error):
		print error

	def on_close(self, ws):
		print "connection closed"

	def on_open(self, ws):
		print "connected"

if __name__ == "__main__":
	client = WSClient()

Leave a Reply

Your email address will not be published. Required fields are marked *