Monday, May 11, 2015

Python socket server to send camera image to client

Simple server run on Raspberry Pi to send jpg from Camera Module to client. Can be viewed on browsers at http://<Raspberry Pi IP>:8000.


pyCamJpgServer.py
import io
import socket
import picamera

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
    
with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.start_preview()

    connection = server_socket.accept()[0].makefile('wb')
    print("Connecting")

    try:
        stream = io.BytesIO()
        camera.capture(stream, 'jpeg')
        stream.seek(0)
        connection.write(stream.read())
        stream.seek(0)
        stream.truncate()

    finally:
        connection.close()
        server_socket.close()
        camera.stop_preview()
        print("Connection closed")



In this example, the server will exit after image sent. To stay waiting next connection, refer to next post.

1 comment:

Fikr said...

A newbie here, how does the browser recognized the incoming TCP packet as an image without running any kind of web server? This is excellent!!!