to generate test file head -c 100000 /dev/urandom > t.txt
was used
Last active
December 25, 2015 08:29
-
-
Save fesor/6947558 to your computer and use it in GitHub Desktop.
Working with OOB messages
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 socket | |
import sys | |
def write_progress(transmitter): | |
sys.stdout.write('\rTransmitted %d bytes' % transmitter) | |
sys.stdout.flush() | |
HOST = 'localhost' # The remote host | |
PORT = 8086 # The same port as used by the server | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((HOST, PORT)) | |
received = 0 | |
while True: | |
try: | |
flag = s.recv(1, socket.MSG_OOB) | |
except socket.error, value: #(value,message): | |
flag = None | |
if flag: | |
write_progress(received) | |
else: | |
#recv usual data | |
data = s.recv(64) | |
if not data: | |
break | |
received += len(data) | |
write_progress(received) | |
print '\n' | |
s.close() |
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 socket | |
import time | |
port = 8086 | |
host = 'localhost' | |
file_obj = file('t.txt') | |
def read_file_by_chunks(file_obj, chunk_size): | |
""" Reads file by fixed-length chunks | |
:type file_obj: file | |
""" | |
file_obj.seek(0) | |
while True: | |
chunk = file_obj.read(chunk_size) | |
if not chunk: | |
break | |
yield chunk | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
s.bind((host, port)) | |
s.listen(1) | |
conn, addr = s.accept() | |
received = 0 | |
i = 0 | |
for chunk in read_file_by_chunks(file_obj, 64): | |
i += 1 | |
received += len(chunk) | |
conn.send(chunk) | |
# each 2 iteration force client to show progress | |
if i % 2 == 0: | |
conn.send('!', socket.MSG_OOB) | |
time.sleep(1) # 1 seconds delay | |
conn.close() | |
s.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment