Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- from os.path import exists, splitext
- from threading import Thread
- # Thread to listen one particular client
- class ClientListener(Thread):
- def __init__(self, sock: socket.socket):
- super().__init__(daemon=True)
- self.sock = sock
- def run(self):
- #getting filename and first piece of file
- #they are splitted by special FS (file separator) character
- chunk = self.sock.recv(1024)
- filename, data = chunk.split(b'\034', 1)
- path = filename.decode('utf-8')
- name, format = splitext(path)
- i = 0
- while exists(path):
- path = name + '_copy' + str('' if i == 0 else i) + format
- i += 1
- with open(path, 'wb+') as file:
- file.write(data)
- while True:
- # try to read 1024 bytes from user
- # this is blocking call, thread will be paused here
- data = self.sock.recv(1024)
- if data:
- file.write(data)
- else:
- # if we got no data – client has disconnected
- file.close()
- print("Connection from", addr, 'is closed')
- # finish the thread
- return
- # AF_INET – IPv4, SOCK_STREAM – TCP
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- # reuse address; in OS address will be reserved after app closed for a while
- # so if we close and immediately start server again – we'll get error
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- # listen to all interfaces at 1234 port
- sock.bind(('', 1234))
- sock.listen()
- while True:
- # blocking call, waiting for new client to connect
- con, addr = sock.accept()
- print("Connection from", addr)
- # start new thread to deal with client
- ClientListener(con).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement