- I'm using the argparse module to allow me to change key information (IP address, port, debug information) from the command line. The default is to use port 12345 on localhost.
- The server simply takes a photo and sends it to the client.
- The server runs forever until the process is stopped (ideally with CTRL-C).
pi@picam:~/Python/camserver $ ./image-server.py -i 192.168.1.106 --debug
Server started on 192.168.1.106:12345
Because I've used the --debug flag, the server tells me it has started and the address and port number it's using.
The code
#!/usr/bin/env python3 import socketserver import argparse import sys import time from io import BytesIO from picamera import PiCamera class ImageHandler(socketserver.BaseRequestHandler): def handle(self): global camera global args try: if args.debug: print("Connection from {}".format(self.client_address[0])) stream = BytesIO() camera.capture(stream, format='jpeg') stream.seek(0) self.request.sendall(stream.getvalue()) if args.debug: print("Image sent.") except Exception as e: print("Server exception") print(e) return class ImageServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def __init__ (self, server_address, handler_class=ImageHandler): socketserver.TCPServer.__init__(self, server_address, handler_class) return if __name__ == '__main__': parser = argparse.ArgumentParser(description='Image server.') parser.add_argument('--hostip', '-i', action='store', dest='address', default='127.0.0.1', help='IP address of server host.') parser.add_argument('--port', '-p', action='store', type=int, dest='port', default=12345, help='Port number.') parser.add_argument('--debug', '-d', action='store_true', default=False, dest='debug', help='Print debugging information.') args = parser.parse_args() try: camera = PiCamera() time.sleep(2) server = ImageServer((args.address, args.port), ImageHandler) if args.debug: print("Server started on {}:{}".format(args.address, args.port)) server.serve_forever() except Exception as e: print(e) except KeyboardInterrupt: if args.debug: print("Server stopped.\n\n")
No comments:
Post a Comment