コード例 #1
0
def Server(port):
    """
    Creates the server instance, sets it up
    """
    host = 'localhost'
    port = int(port)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((host, port))
    server.listen(5)

    # blocking call to accept()
    print 'Waiting for partner to join conversation...\n'
    (conn, client_addr) = server.accept()
    print 'Client connected: ', client_addr[0]

    # wait to receive client's public key
    key = conn.recv(1024)
    key = key.split(',')
    keyTuple = (key[0], key[1])
    print 'Client\'s Public Key received'

    e, d, c = miniRSA.keygen()
    sendPublic = str(d) + ',' + str(c)
    conn.send(sendPublic)
    print 'Public Key sent'

    privateTuple = (e, c)

    print 'Type your message below and hit enter to send. Type \'EXIT\' to end conversation.\n'

    ReadThread = Thread_Manager('read', conn, keyTuple, None)
    WriteThread = Thread_Manager('write', conn, None, privateTuple)

    ReadThread.start()
    WriteThread.start()

    # wait until client dc's
    ReadThread.join()
    print 'Your partner has left the conversation. Press any key to continue...\n'

    # stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # shut down client connection
    try:
        conn.shutdown(socket.SHUT_RDWR)
        conn.close()
    except:
        # connection already closed
        pass

    # shut down server
    print 'Shutting server down...'
    server.shutdown(socket.SHUT_RDWR)
    server.close()

    return 0
コード例 #2
0
def Client(port):
    """
    Creates the client instance, sets up the client
    """

    host = 'localhost'
    port = int(port)

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))

    e, d, c = miniRSA.keygen()
    sendPublic = str(d) + "," + str(c)
    client.send(sendPublic)
    print 'Public key sent'

    key = client.recv(1024)
    key = key.split(',')
    keyTuple = (key[0], key[1])
    print 'Server\'s Public Key received'

    privateTuple = (e, c)

    print 'Connected to chat. Type your messages below and hit enter to send. Send \'EXIT\' to leave the conversation.\n'

    ReadThread = Thread_Manager('read', client, keyTuple, None)
    WriteThread = Thread_Manager('write', client, None, privateTuple)

    ReadThread.start()
    WriteThread.start()

    ReadThread.join()
    print 'Your partner has left the conversation. Press any key to continue...\n'

    # stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # shut down client connection
    try:
        client.shutdown(socket.SHUT_RDWR)
        client.close()
    except:
        # connection already killed
        pass