forked from 7543distrofiuba/sockets-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
66 lines (50 loc) · 1.39 KB
/
server.py
File metadata and controls
66 lines (50 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import argparse
import socket
import time
import os
from constants import CHUNK_SIZE
def get_timestamp():
return int(round(time.time()*1000))
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", default="127.0.0.1")
parser.add_argument("-P", "--port", type=int, default="8080")
return parser.parse_args()
def main():
args = parse_arguments()
host = args.host
port = int(os.environ.get("PORT", args.port))
address = (host, port)
print(f"adress - host: {host}, port: {port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Binding...')
sock.bind(address)
print('Binding ok')
print('Liten...')
sock.listen(1)
print('Liten ok')
while True:
conn, addr = sock.accept()
if not conn:
break
print(f"{get_timestamp()} - Accepted connection from {addr}")
bytes_received = 0
size = conn.recv(CHUNK_SIZE).decode()
print(f"Size? - {size}")
if not size:
continue
size = int(size)
print(f"Size - {size}")
conn.send(b'start')
print(f"Receiving...")
while bytes_received < size:
data = conn.recv(CHUNK_SIZE)
bytes_received += len(data)
print(f"data: {data}")
print(f"Receiving ok")
# Send number of bytes received
conn.send(str(bytes_received).encode())
sock.close()
if __name__ == "__main__":
print("Inilcializando server...")
main()