Skip to content

Instantly share code, notes, and snippets.

@shavit
Created October 14, 2016 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shavit/1c7be17f047dfc5ada4801fb5bfba6e8 to your computer and use it in GitHub Desktop.
Save shavit/1c7be17f047dfc5ada4801fb5bfba6e8 to your computer and use it in GitHub Desktop.
Broadcast to server and stream binary files with python
import os
import socket
videos = []
client = socket.socket()
client.connect((socket.gethostbyname('localhost'), 3000))
# Append the video files paths into array
def load_videos():
base_dir = os.path.dirname(os.path.realpath(__file__))
videos_dir = os.path.join(base_dir, 'videos')
for video in os.listdir(videos_dir):
if video.lower().endswith('.mp4'):
videos.append(os.path.join(videos_dir, video))
pass
def main():
load_videos()
# Read the first video in bytes
with open(videos[0], 'rb') as f:
i = 0
while True:
buf = f.read(24)
# Check for EOF
if buf == '':
break
# Stream the data using the socket
client.send(buf)
i += 1
print('---> Reading from buffer {}'.format(i))
pass
# If running as the main script and not loaded as a module
if __name__ == '__main__':
print('---> Starting main script')
main()
#
# Listen to localhost:3000. Read binary data using 512 bytes buffer.
# This example was made to test if the client streams videos files. It makes it ease to test from script instead of
# IP or video camera.
#
import socket
server = socket.socket()
server.bind((socket.gethostbyname('localhost'), 3000))
server.listen(10)
while True:
i = 0
connection, address = server.accept()
print('---> Receive a connection from {}'.format(address))
# Read the data
while True:
data = connection.recv(512)
i += 1
print('---> Reading bytes {}'.format(i))
if not data:
break
# Send response when finish reading
connection.send('It worked'.encode('utf-8'))
connection.close()
if __name__ == '__main__':
print('---> Starting server on localhost:3000')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment