#!/usr/bin/env python3 from socket import * from _thread import start_new_thread from struct import pack, unpack # Create a socket. This doesn't open a port or anything yet # Parameters: # AF_INET is ipv4, AF_INET6 # SOCK_STREAM means TCP, SOCK_DGRAM would be UDP our_socket = socket(AF_INET, SOCK_STREAM) # Bind is only for servers, not client # clients call connect instead # Still doesn't open it, although we have an address # Double parenthesis = 1 argument which is a tuple our_socket.bind(("0.0.0.0", 5111)) # Actually opens the port # Argument is a queue of connections to accept our_socket.listen(5) def handle_client(client_socket): while True: try: data = client_socket.recv(9, MSG_WAITALL) # We'll get 8 bytes op, a, b = unpack("!Bii", data) if(op == ord('+')): c = a + b elif(op == ord('*')): c = a * b elif(op == 0): print("Client gracefully disconnected") break # Then send the result data_to_send = pack("!i", c) client_socket.send(data_to_send) except: print("Something is wrong with that client") break client_socket.close() while True: client_socket, client_address = our_socket.accept() print("We got a new connection from: ", client_address[0], client_address[1]) start_new_thread(handle_client, (client_socket, )) our_socket.close()