Python套接字未发送数据包

时间:2019-02-27 04:31:21

标签: python python-3.x sockets tcp

我正在使用套接字库在Python中创建一个简单的消息传递服务器和客户端。首先,在允许用户发送消息之前,我先进行一些验证和密钥交换。我偶尔会遇到一个问题,服务器将发送一条消息,而客户端将不会接收到消息,然后服务器将继续尝试接收一条消息,但是客户端也仍然在接收呼叫上处于阻塞状态,因此它们陷入僵局。我很困惑这是怎么回事,因为我认为套接字API运行了TCP,应该保证可以交付。

这是服务器端的一部分:

def serverSocket():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind(('0.0.0.0', 2048))
    s.listen()
    conn, addr = s.accept()
    print("Connected by {}".format(addr))
    with conn:
        ## Start diffie helman

        # generate a list of primes
        primes = primesSieve()

        # pick g
        g = pickPrime(500, primes)

        # send g
        printDebug("Sending g")
        conn.send(bytes(str(g), 'utf-8'))
        printDebug("Sent g")

        # pick p
        p = pickPrime(500, primes, g)

        # send p
        printDebug("Sending p")
        conn.send(bytes(str(p), 'utf-8'))
        printDebug("Sent p")

        # pick a
        a = random.randint(500, 2000)

        # calculate A
        A = (g**a)%p

        # send A
        printDebug("Sending A")
        conn.send(bytes(str(A), 'utf-8'))
        printDebug("Sent A")

        # receive B
        printDebug("Receiving B")
        data = conn.recv(1024)  #### This is where the server will stop
        printDebug("Received B")

        # convert B TODO error checking
        B = int(data.decode('utf-8'))

        # evaluate key
        key = (B**a)%p

这是客户端的一部分:

def clientSocket():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(('0.0.0.0', 2048))

    ## Start diffie helman
    # receive g
    printDebug("Receiving g")
    g = s.recv(1024).decode('utf-8')
    printDebug("Received g")

    g = int(g)
    # receive p
    printDebug("Receiving p")
    p = s.recv(1024).decode('utf-8')
    printDebug("Received p")

    p = int(p)
    # receive A
    printDebug("Receiving A")
    data = s.recv(1024)  #### This is where the client will stop
    printDebug("Received A")

    # convert A TODO error checking
    A = int(data.decode('utf-8'))
    # pick b
    b = random.randint(500, 2000)
    printDebug(b)
    B = (g ** b) % p
    printDebug(B)
    # send B
    printDebug("Sending B")
    s.send(bytes(str(B), 'utf-8'))
    printDebug("Sent B")

    # evaluate key
    key = (A ** b) % p

大多数情况下,这种方法都可以正常工作。但是有时候,当客户端尝试接收A时,服务器会发送它,然后继续接收B,但是客户端却永远不会收到A并且不会继续前进。

感谢您的帮助。 我也知道这真的不是做Diffie Hellman的最好方法,而且数字还不够大。

1 个答案:

答案 0 :(得分:0)

正如@ user207421在他的评论中所说,我已经在阅读它们,因为它收到了不止一条消息。