使用套接字

时间:2016-05-06 17:59:50

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

您好我已经使用python中的套接字传输文件来建立客户端和服务器架构。它在windows中运行得很好,但在ubuntu中它不起作用。在Ubuntu中没有错误,但整个文件没有被发送。如果我尝试发送4mb的音乐文件,在Windows中只传输50-60kb甚至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上运行?

1 个答案:

答案 0 :(得分:0)

有时,数据被分成更小的部分,并通过网络接口以多个段发送,而不是一次性发送。基本上,在关闭网络连接之前,您没有收到整个消息。您需要添加一些内容来检查是否已收到数据(即,使用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()