【问题标题】:Client Not Receiving Data in Python客户端未在 Python 中接收数据
【发布时间】:2023-03-07 04:27:01
【问题描述】:

我对 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()

客户:

 # the specified libraries
 import socket
 import M2Crypto as m2c
 #file to be transferred
 FILE = open("test.txt", "r")
 #address of the server
 server_addr = '10.1.1.2'
 #port the server is listening on
 dest_port = 8888

 data = FILE.read()


 #Creates a socket for the transfer
 mysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
 mysocket.connect( (server_addr, dest_port) )

 data = mysocket.recv(1024)
 print data
 #creates a new file to store the msg
 name = "serverPubKey.pem"

 #opens the new file and writes the msg to it
 FILE = open (name, "w")
 FILE.write(data)


 #closes the socket.
 mysocket.close()

我将不胜感激有关此事的任何帮助。谢谢!

【问题讨论】:

    标签: python sockets client-server broken-pipe


    【解决方案1】:

    在这样的应用程序中,有时绕过低级细节并使用 socket.makefile 及其更高级别的 API 会有所帮助。

    在客户端关闭中,替换:

    data = mysocket.recv(1024)
    

    与:

    f = mysocket.makefile('rb')
    data = f.read(1024)           # or any other file method call you need
    

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

    【讨论】:

      【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 2020-02-05
        • 2019-08-13
        • 2016-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多