Python服务器 - 客户端关系网络问题

时间:2012-03-23 15:26:26

标签: python

我为我的网络类编写了一个程序,它通过在套接字上发送文件并对传输进行计时来测量上传和下载速度,我使用了Python。我遇到的问题是服务器和客户端在同一台机器上运行时可以正常通话,但只要我将服务器程序放在网络上的另一台机器上,就不会发生文件传输。他们彼此交谈(客户说"连接到服务器"服务器说"连接来自xxx.xxx.xxx.xxx")但文件传输大小和速度显示为0和0.

这是服务器代码:

import util
import socket
import os
import shutil
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
f = open("receivedfromclient.txt", "r+")
print "Waiting for clients..."
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print "Client connected:", addr
start = time.clock()
msg = c.recv(257024)
stop = time.clock()
duration = stop-start
f.write(str(msg))
b = os.path.getsize("receivedfromclient.txt")
print "File size = ", b, "bits"
print "Time to transfer from client  = ", duration, " seconds"
bw = (b/duration)/1048576
print "The upload bit rate is ", bw, "Mpbs"
f.close()
shutil.copy("receivedfromclient.txt", "sendtoclient.txt")
f.open("sendtoclient.txt")
c.send(f.read())
f.close()
c.close()
s.close()

,客户端代码类似:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Please enter host address: ")#socket.gethostname()
port = 12345
sendfile = raw_input("Please enter name of file to transfer: ")
f = open(sendfile,"rb")
g = open("receivedfromserver.txt","w")
print "Connecting to ", host, port
s.connect((host, port))
s.send(f.read())

等等。谁能告诉我我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

嗯 - 至少有一些问题:

主要的是,恕我直言,目前尚不清楚你真正想做什么。

以下是您的代码,其中包含一些注释:

# import util <-- NOT NEEDED
import socket
import os
import shutil
import time # <-- Added
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
f = open("receivedfromclient.txt", "r+")
print "Waiting for clients..."
s.bind((host, port))
s.listen(5)
c, addr = s.accept() # <-- FORGOTTEN ()
print "Client connected:", addr
start = time.clock()
msg = c.recv(257024) # <-- You need some loop here to get the whole file
stop = time.clock()
duration = stop-start
f.write(str(msg))
b = os.path.getsize("receivedfromclient.txt") # <-- = instead of .
print "File size = ", b, "bits"
print "Time to transfer from client  = ", duration, " seconds"
bw = (b/duration)/1048576
print "The upload bit rate is ", bw, "Mpbs"
f.close()
shutil.copy("receivedfromclient.txt", "sendtoclient.txt")
f.open("sendtoclient.txt")
c.send(f.read())
f.close()
c.close()
s.close()

这里的一个问题是,开始时大部分情况都等于停止 - 所以你在(b/duration)中得到一个除零错误。

在客户端部分中至少缺少import socket个;根本不需要g

请进一步解释,你想做什么。

如果你想传输文件,有很多方法可以做(sftp,rsync,nc,...)。