Skip to content

Instantly share code, notes, and snippets.



Created Oct 14, 2016
What would you like to do?
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))
def main():
# Read the first video in bytes
with open(videos[0], 'rb') as f:
i = 0
while True:
buf =
# Check for EOF
if buf == '':
# Stream the data using the socket
i += 1
print('---> Reading from buffer {}'.format(i))
# If running as the main script and not loaded as a module
if __name__ == '__main__':
print('---> Starting main script')
# 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))
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:
# Send response when finish reading
connection.send('It worked'.encode('utf-8'))
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