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(imageFile.read())
	 
	def open(self):
		print 'new connection'
		self.write_message(self.str)
	 
	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)
	http_server.listen(8888)
	tornado.ioloop.IOLoop.instance().start()

Client code:

from PIL import Image
import websocket
import cStringIO
import base64

class WSClient():

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

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

	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 *