【问题标题】:File Transfer in python using socket使用套接字在python中传输文件
【发布时间】:2016-05-07 02:12:33
【问题描述】:

您好,我已经使用 Python 中的套接字创建了一个客户端和服务器架构来传输文件。它在 Windows 中工作得非常好,但在 ubuntu 中它不起作用。在 Ubuntu 中没有错误,但没有发送整个文件。如果我尝试发送 4mb 的音乐文件,则只有 50-60kb 被传输,而在 Windows 中,即使是 300mb 的文件也可以完美发送。这是我的代码。

客户-

def sendFile(self):
    # ''' Print a language constructed from
    #     the selections made by the user. '''
    # print('%s!' % (self.recipient.displayText()))
    client_socket.send("upload")
    time.sleep(1)
    client_socket.send(self.virtual_os[self.os_box.currentIndex()].title())
    time.sleep(1)
    path = self.recipient.displayText() #inputbox which contains the path of the file
    self.recipient.setText('')
    name = path.split('/')
    name = name[len(name)-1]
    print "Opening file - ",name
    client_socket.send(name)
    time.sleep(1)
    fp = open(path,'rb')
    data = fp.read()
    fp.close()
    size = os.path.getsize(path)
    size = str(size)
    client_socket.send(size)
    time.sleep(1)
    client_socket.send(data)
    print "Data sent successfully"

服务器-

choice = client_socket.recv(1024)
if(choice == "upload"):
    virtual_os = client_socket.recv(1024)
    print virtual_os
    fname = client_socket.recv(1024)
    print "recieved file "+fname
    size = client_socket.recv(1024)
    size = int(size)
    print "The file size is - ",size," bytes"
    size = size*2
    strng = client_socket.recv(size)
    fp = open(fname,'wb')
    fp.write(strng)
    fp.close()
    print "Data Received successfully"

我的代码有问题还是我必须更改某些内容才能使其在 Ubuntu 上运行?

【问题讨论】:

  • 为什么不直接使用len(data) 而不是os.path.getsize()
  • os.path.getsize() 工作正常,因为我打印了大小并且它打印了正确的大小,但是我尝试使用 len(data) 仍然不起作用。问题只在 Ubuntu 中。不知何故,只发送了一部分数据。

标签: python python-2.7 sockets ubuntu file-transfer


【解决方案1】:

有时数据会被分块成更小的部分,并通过网络接口在多个段中发送,而不是一次全部发送。基本上,在关闭网络连接之前,您不会收到完整的消息。您需要添加一些东西来检查是否已收到数据(即,一个 while 循环来检查数据的大小是否为 0)。我从官方 Python 页面https://docs.python.org/2/library/socket.html#example 中的一个示例中得到以下内容@

# Echo server program
import socket

HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

【讨论】:

  • 这个我也试过了!我主要担心的是,如果相同的代码在 Windows 上运行,为什么它不能在 ubuntu 上运行?
  • 您在测试中是否使用了环回接口(即localhost127.0.0.1)?通过环回发送时有一些复杂性,例如“扩展”缓冲区以容纳数据(尽管不要引用我的话)。在任何情况下,您都应该使用 wireshark 或 tcpdump 来查看发生了什么。仅供参考,wireshark 无法在 Windows 上使用 localhost。
猜你喜欢
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多