1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #!/bin/python3
- import socket
- import sys
- import random
- import time
- import math
- from PIL import Image
- im = Image.open("wave.gif")
- N_ROWS = 5
- N_COLS = 10
- oldPing = time.time()
- # Create a TCP/IP socket
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- # Connect the socket to the port where the server is listening
- server_address = ('0.0.0.0', 2020)
- print('binding {} port {}'.format(*server_address))
- sock.bind(server_address)
- sock.settimeout(30)
- def getBytes(im):
- x = im.load()
- pixels = [0] * (N_ROWS * N_COLS)
- for row in range(N_ROWS):
- for col in range(N_COLS):
- pixels[row*N_COLS + col] = int(int(x[col, row]/16) + random.random() * (x[col, row]-int(x[col, row])))
- pixels[49] = int(pixels[49]/2)
- return bytes([0x41] + pixels)
- frames = []
- try:
- while 1:
- im.seek(im.tell()+1)
- im.thumbnail((N_COLS, N_ROWS), Image.ANTIALIAS)
- pixels = getBytes(im)
- frames.append(pixels)
- except EOFError:
- pass
- client_address = None
- frameIndex = 0
- print('frame count:', len(frames))
- if not frames:
- exit(1)
- try:
- while True:
- if not client_address:
- try:
- print('waiting...')
- data, addr = sock.recvfrom(16)
- print('received {} from {}'.format(data, addr))
- client_address = addr
- except socket.timeout:
- pass
- else:
- sock.sendto(frames[frameIndex], client_address)
- frameIndex = (frameIndex+1) % len(frames)
- if time.time() - oldPing > 30:
- try:
- data, addr = sock.recvfrom(16)
- print('received {} from {}'.format(data, addr))
- client_address = addr
- oldPing = time.time()
- except socket.timeout:
- client_address = None
- time.sleep(1/40)
- except KeyboardInterrupt:
- pass
- finally:
- print('closing socket')
- sock.close()
|