我已经编写了以下用于文件传输的python代码。它在localhost环境中工作正常。它在两台不同的物理机器之间失败。我得到的文件,但数据不完整。将文件大小发送到客户端时将字符串转换为long时也存在无效的文字错误。我无法弄清楚为什么?
server.py
from socket import *
import thread
import os
l = {}
def handler(clientsocket, clientaddr):
print "Accepted connection from: ", clientaddr
while 1:
data = clientsocket.recv(8192)
if not data:
break
else:
print "The following data was received - ",data
l[clientaddr] = data
print l
print "Opening file - ",data
fp = open(data,'r')
size = os.path.getsize(data)
clientsocket.send(str(size))
strng = "hi"
print size
while size > 0:
strng = fp.read(8192)
clientsocket.send (strng)
size = size - 8192
clientsocket.close()
if __name__ == "__main__":
host = 'localhost'
port = 55573
buf = 8192
addr = (host, port)
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.bind(addr)
serversocket.listen(5)
while 1:
print "Server is listening for connections\n"
clientsocket, clientaddr = serversocket.accept()
thread.start_new_thread(handler, (clientsocket, clientaddr))
serversocket.close()
client.py
from socket import *
import os
if __name__ == '__main__':
host = '10.1.99.176'
port = 55573
buf = 8192
addr = (host, port)
clientsocket = socket(AF_INET, SOCK_STREAM)
clientsocket.connect(addr)
while 1:
fname = raw_input("Enter the file name that u want>> ")
if not fname:
break
else:
clientsocket.send(fname)
print "\nThe file will be saved and opened- "
fname = '/home/coep/Downloads/'+fname
nf = open(fname,"a")
strng = "hi"
size = clientsocket.recv(16)
size = long(size)
print size
while size > 0:
strng = clientsocket.recv(8192)
if not strng:
break
nf.write(strng)
size = size - 8192
if size > 500000:
print size
nf.close()
fname = 'viewnior '+ fname
print fname
os.system(fname)
答案 0 :(得分:1)
在server.py中,您正在使用
host ='localhost',它只是将端口绑定到localhost IP地址,即127.0.0.1。
将其更改为host ='0.0.0.0',它会将特定端口绑定到所有可用接口。
更新:另一个原因可能是缓冲区大小太大而且有8192,它可能永远被阻止,因为上次传输永远无法填充缓冲区。要绕过它,如果缓冲区没有填满,请将超时设置为makeure以继续。在client.py中,尝试更改,
clientsocket.timeout(5)
while size > 0:
try:
strng = clientsocket.recv(8192)
if not strng:
break
nf.write(strng)
size = size - 8192
if size > 500000:
print size
except:
nf.write(string)
8192也是相当大的尺寸,并尝试将大小减小到1000-1300字节。 Chossing 8192没有给你带来任何好处,因为数据包仍将在片段上移动,MTU上限通常为1436字节。