未在Python中接收数据的客户端

2024-09-29 23:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,有一个基本的问题,一个网络套接字连接的客户端可以接收数据吗?在我的问题中,客户是启动连接的人,这可能很明显,但我想说清楚。我这样问是因为我有另一个服务器和客户机(都是python),允许服务器从客户机接收文件。它工作得很好,但是我不能得到一个客户端接收文件的例子。Python一直告诉我管道已经损坏,我怀疑是因为在客户端我使用了data = mysocket.recv(1024)行。我怀疑客户机看不到任何数据流,从而关闭了与服务器的连接。服务器将其视为断开的管道。服务器和客户端在下面。在

服务器:

 #libraries to import
 import socket
 import os
 import sys
 import M2Crypto as m2c

 #information about the server the size of the message being transferred
 server_address = '10.1.1.2'
 key_port = 8888
 max_transfer_block = 1024

 FILE = open("sPub.pem","r")

 #socket for public key transfer
 keysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
 keysocket.bind((server_address, key_port))
 keysocket.listen(1)

 while 1:
         conn, client_addr = keysocket.accept()
         print 'connected by', client_addr
         #sends data to the client
         data = FILE.read()
         keysocket.sendall(data)
 keysocket.close()

客户:

^{pr2}$

在这件事上我会很感激的。谢谢!在


Tags: 文件thetokeyimport服务器client客户端
2条回答

另外,加上前面的评论,一个好的测试有时是重复接收几次。一次性捕获服务器发送的信息的可能性不大。在

像这样的东西

nreceive = True#nreceive = Not Received
ticks = 0
f = None
while nreceive and ticks < 101:#try to get the info 100 times or until it's received
    ticks+=1
    try:
        f = mysocket.makefile('rb')
        if not f == None:
            nreceive = False
    except:
        pass
data = f.read(1024)

在这样的应用程序中,有时可以绕过低级细节,而将socket.makefile与其高级API一起使用。在

在客户端关闭中,替换:

data = mysocket.recv(1024)

有:

^{pr2}$

source code for ftplib显示了如何在生产代码中执行此操作。在

相关问题 更多 >

    热门问题