Example #1
0
def server(reqcode):
    #retrieve the IP address of server's machine
    hostname = socket.gethostbyname(socket.gethostname())
    
    serverSocket = getsocket(socket.SOCK_STREAM)
    print 'SERVER_PORT=' + str(serverSocket.getsockname()[1])
    
    #start listening, queue 0 connections because we only have one client at a time
    serverSocket.listen(0)
    

    while True:
        sys.stderr.write('Accepting Connection...\n')
        conn, addr = serverSocket.accept()

        # accept a TCP connection from the client
        # conn is the socket endpoint of the client and addr is the address bound to conn
        # receive 32 bytes, enough size for an integer
        data = conn.recv(32)
        
        if reqcode != data:
            # received incorrect req_code from client, close TCP connection with client
            conn.shutdown(1)
            continue
        
        # create a UDP socket
        serverUDP = getsocket(socket.SOCK_DGRAM)

        # send the port number bound to the UDP socket over to the client
        conn.sendall(str(serverUDP.getsockname()[1]))
       
        # receive the message from client
        sys.stderr.write('Waiting to receive message...\n')
        message, clientaddr = udpreceiver(serverUDP, BUFSIZE)

        #reverse message
        message = message[::-1]

        sys.stderr.write('Sending reversed message to client...\n')
        udpsender(serverUDP, message, clientaddr)

        # close UDP socket
        serverUDP.close()

    # close TCP connection
    serverSocket.close()
Example #2
0
def client(saddr, nport, reqcode, message):
    #retrieve the IP address of server's machine
    hostname = socket.gethostbyname(socket.gethostname())

    clientSocket = getsocket(socket.SOCK_STREAM)

    # connect to server's socket
    try:
        clientSocket.connect((saddr, int(nport)))
    except socket.error:
        sys.stderr.write('Connection to server failed\n')
        exit(-1)
    
    # send reqcode to server
    clientSocket.sendall(reqcode)

    # receive the UDP port used by the server
    # enough size for a port number
    udpport = clientSocket.recv(16)

    # check if the server gives us the okay sign
    if udpport == '':
        sys.stderr.write('Given request code is incorrect\n')
        clientSocket.close()
        exit(-1)

    # close TCP connection
    clientSocket.close()

    # create a UDP socket and send message, make sure the data is all sent
    clientSocket = getsocket(socket.SOCK_DGRAM)
    
    bytesSent = 0
    sendaddr = (saddr, int(udpport))

    # send the message through udp socket to server
    udpsender(clientSocket, message, sendaddr)

    # receive the reversed message through udp socket from server
    reversedMsg = udpreceiver(clientSocket, BUFSIZE)[0]
    print reversedMsg
	
	# close socket
    clientSocket.close()