import socket import sys # save request code, make var for tcp socket port requestcode = sys.argv[1] rport = 0 # start udp socket, declare tcp socket var sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) tsock = None # get udp socket port from system, save in a var sock.bind(('', 0)) nport = sock.getsockname()[1] print("SERVER_PORT=", nport, sep="") # make flag to see if we are waiting for a confirmation or a new connection newConn = True # listen for msgs while True: message, clientAddress = sock.recvfrom(1024) message = message.decode() # match, create tcp socket if (message == requestcode and newConn): tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tsock.bind(('', 0)) rport = tsock.getsockname()[1] print("SERVER_TCP_PORT=", rport, sep="") sock.sendto(str(rport).encode(), clientAddress) # send new socket port to client newConn = False # get confirmation of port, send OK confirm, newaddr = sock.recvfrom(1024) if (confirm.decode() == str(rport)): sock.sendto("correct".encode(), newaddr) else: print("Received wrong port number, fail") exit(1) tsock.listen(1) # now put logic for TCP socket behaviour #while True: tempsock, addr = tsock.accept() msg = tempsock.recv(1024).decode() print("SERVER_RCV_MSG='", msg, "'", sep="") reply = msg[::-1] tempsock.send(reply.encode()) newConn = True tempsock.close() # match, send a confirmation msg elif (newConn == False and message == rport): sock.sendto("correct".encode(), clientAddress) # client screwed up something other than sending the wrong requestcode elif (newConn != False): newConn = True tsock.close()