Last active
September 29, 2017 13:58
-
-
Save weedge/f87e84805b1e646514e17c2a6b1c8978 to your computer and use it in GitHub Desktop.
simple photograph server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import socket | |
import struct | |
#u should do this: | |
# pip install --upgrade pip | |
# pip install image | |
from PIL import Image | |
# NOTICE: | |
# The server script should be run first (don't run in pi)· | |
# to ensure there’s a listening socket ready to accept a connection from the client script | |
# Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means all interfaces) | |
server_socket = socket.socket() | |
server_socket.bind(('0.0.0.0', 8000)) | |
server_socket.listen(0) | |
# Accept a single connection and make a file-like object out of it | |
# @TODO: use select/poll or use epoll/kqueue for more connections 10k> | |
connection = server_socket.accept()[0].makefile('rb') | |
try: | |
while True: | |
# Read the length of the image as a 32-bit unsigned int. If the | |
# length is zero, quit the loop | |
image_len = struct.unpack('<L', connection.read(4))[0] | |
if not image_len: | |
break | |
# Construct a stream to hold the image data and read the image | |
# data from the connection | |
image_stream = io.BytesIO() | |
image_stream.write(connection.read(image_len)) | |
# Rewind the stream, open it as an image with PIL and do some | |
# processing on it | |
image_stream.seek(0) | |
image = Image.open(image_stream) | |
print('Image is %dx%d' % image.size) | |
image.verify() | |
print('Image is verified') | |
finally: | |
connection.close() | |
server_socket.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment