Skip to content

Instantly share code, notes, and snippets.

@marvin
Created December 17, 2012 13:50
Show Gist options
  • Save marvin/4318413 to your computer and use it in GitHub Desktop.
Save marvin/4318413 to your computer and use it in GitHub Desktop.
simple python client/server socket binary stream
import socket
HOST = 'localhost'
PORT = 9876
ADDR = (HOST,PORT)
BUFSIZE = 4096
videofile = "videos/royalty-free_footage_wien_18_640x360.mp4"
bytes = open(videofile).read()
print len(bytes)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
client.send(bytes)
client.close()
import socket
HOST = ''
PORT = 9876
ADDR = (HOST,PORT)
BUFSIZE = 4096
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(ADDR)
serv.listen(5)
print 'listening ...'
while True:
conn, addr = serv.accept()
print 'client connected ... ', addr
myfile = open('testfile.mov', 'w')
while True:
data = conn.recv(BUFSIZE)
if not data: break
myfile.write(data)
print 'writing file ....'
myfile.close()
print 'finished writing file'
conn.close()
print 'client disconnected'
@zvakanaka
Copy link

Cosmic! And simple to understand

@NagarajuBaydeti
Copy link

I tried the code given, but unfortunately I am getting the error mentioned below:
Traceback (most recent call last):
File "client.py", line 13, in
bytes = open(videoFile,encoding="utf8").read()
File "C:\Users\hP\AppData\Local\Programs\Python\Python36-32\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 5: invalid start byte

@louay075
Copy link

please how can i receive the file when i sent it via this code?

@victor-oliveira1
Copy link

The problem is because the open function is not used to save or send in binary form.
Client:
Change the line 9 to: bytes = open(videofile, 'rb').read()
Server:
Change the line 18 to: myfile = open('testfile.mov', 'wb')

@itachi0071998
Copy link

Instead of video file can I use this code on webcam?

@sajjsamm
Copy link

simple handy code and easy to understand for beginners! thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment