Friday, November 14, 2014

Bare-bones HTTP Image Server in Python

I'm looking at what it would take to integrate the IP camera functionality used by my rover into the main control code, rather than using a separate app to serve up the JPG frames from the camera I've never written a web server before, so I put together a very simple program in Python to figure out the mechanics of sending a JPG file to a requesting HTTP client. It looks like it would be pretty simple to add to the robot code, since the camera callback returns the JPG as a byte array.

This code listens on a socket for an HTTP request - any HTTP request - and completely neglects to check or sanitize the input. It then serves an image back. It works for testing and understanding how things work down at the socket level, and is absolutely unfit for any other purpose. :-)

Tested in Chrome and IE.


#!/usr/bin/env python

import socket

host = ''
port = 8080
backlog = 5
size = 8096

# Read the entire file as a single byte string
with open('test.jpg', 'rb') as f:
    reply = f.read()

while 1:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        s.bind((host,port))
        s.listen(backlog)

        client, address = s.accept()
        print "Got client connection"
        clientReq = client.recv(size)
        print clientReq


        replyLength = len(reply)
        headers = "HTTP/1.x 200 OK\r\n"
        headers = headers + "Content-Length: " + str(replyLength) + "\r\n"
        headers = headers + "Connection: Keep-Alive\r\n"
        headers = headers + "\r\n"

        client.send(headers + reply)
        s.shutdown(1)
        s.close()

No comments:

Post a Comment