我爲我的網絡類編寫了一個程序,它通過在套接字上發送文件並計時傳輸來測量上傳和下載速度,並使用Python。我遇到的問題是服務器和客戶端在同一臺計算機上運行時可以說得很好,但只要將服務器程序放在我的網絡上的另一臺計算機上,就不會發生文件傳輸。他們互相交談(客戶端說「連接到服務器」,服務器說「從xxx.xxx.xxx.xxx連接」),但文件傳輸大小和速度顯示爲0和0.關於網絡問題的Python服務器 - 客戶端關係
這裏是服務器代碼:
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())
等。有人可以告訴我我在做什麼錯嗎?
首先,'s.accept'應該變成's.accept()'。 – Marcin 2012-03-23 15:34:00
這就是你正在運行的代碼嗎? 's.accept'應該是's.accept()'。 'b.os.path.getsize'應該是'b = os.path.getsize' – MattH 2012-03-23 15:36:05
不,我有一些拼寫錯誤,現在修正了。我做了s.accept()和b = os.path.getsize。對於那個很抱歉。 – crypto 2012-03-23 18:38:54