#!/usr/bin/env python3 from socket import * 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) print(our_socket) while True: client_socket, client_address = our_socket.accept() print("We got a new connection from: ", client_address[0], client_address[1]) # First, get a math problem from the client # Protocol: Client sends two 4-byte signed integers in network byte order, 8 bytes total while True: try: data = client_socket.recv(8, MSG_WAITALL) # We'll get 8 bytes a, b = unpack("!ii", data) except: print("Something is wrong with that client") break print("We got a = ", a, " b = ", b) # Then figure out the answer c = a + b # Then send the result data_to_send = pack("!i", c) client_socket.send(data_to_send) client_socket.close() our_socket.close()