uaveiro-leci/2ano/1semestre/rc1/pratica06/SocketsPython_code/serverTCPv2.py

45 lines
1.2 KiB
Python
Raw Permalink Normal View History

import socket
import threading
import signal
import sys
import struct
def signal_handler(sig, frame):
print('\nDone!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C to exit...')
##
def handle_client_connection(client_socket,address):
print('Accepted connection from {}:{}'.format(address[0], address[1]))
try:
while True:
request = client_socket.recv(29)
if not request:
client_socket.close()
else:
pkt=struct.unpack('!BLL20s',request)
print(pkt)
print('Received ver: {}, order: {}, size: {} -> {}'.format(pkt[0],pkt[1],pkt[2],pkt[3].decode()))
except (socket.timeout, socket.error):
print('Client {} error. Done!'.format(address))
ip_addr = "0.0.0.0"
tcp_port = 5005
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip_addr, tcp_port))
server.listen(5) # max backlog of connections
print('Listening on {}:{}'.format(ip_addr, tcp_port))
while True:
client_sock, address = server.accept()
client_handler = threading.Thread(target=handle_client_connection,args=(client_sock,address),daemon=True)
client_handler.start()