feat: TCP client-server
This commit is contained in:
parent
c0e7fea3bb
commit
9b3ca71b70
54
connection.py
Normal file
54
connection.py
Normal file
@ -0,0 +1,54 @@
|
||||
import socket
|
||||
import argparse
|
||||
import threading
|
||||
import random
|
||||
import time
|
||||
|
||||
def handle_client(conn):
|
||||
while True:
|
||||
try:
|
||||
num = random.randint(0, 100)
|
||||
conn.send(f"number={num}".encode())
|
||||
time.sleep(1)
|
||||
except:
|
||||
print("Disconnected.")
|
||||
conn.close()
|
||||
break
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('type', type=str, help="'client' or 'server'", default='server')
|
||||
parser.add_argument('--host', type=str, help="server's IPv4 address", default='0.0.0.0')
|
||||
parser.add_argument('--port', type=int, help="server's listening port", default=8888)
|
||||
|
||||
args = parser.parse_args()
|
||||
socket_type = args.type
|
||||
host, port = args.host, args.port
|
||||
|
||||
if socket_type == 'server':
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.bind((host, port))
|
||||
sock.listen(8)
|
||||
|
||||
print("Server listening...")
|
||||
|
||||
while True:
|
||||
conn, addr = sock.accept()
|
||||
print(f"Accept connection from {addr}")
|
||||
|
||||
thread = threading.Thread(target=handle_client, args=(conn, ))
|
||||
thread.start()
|
||||
print('RUNNING THREAD')
|
||||
|
||||
else:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.connect((host, port))
|
||||
|
||||
while True:
|
||||
data = sock.recv(1024)
|
||||
print(data.decode())
|
||||
|
||||
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user