收到到目前爲止,我可以將文件發送到我的「文件服務器」,並從那裏以及檢索文件。但我不能同時做這兩件事。我必須評論其他線程的其中一個工作。正如你將在我的代碼中看到的那樣。試圖建立一個原油發送/ TCP通過在Python
服務器代碼
from socket import *
import threading
import os
# Send file function
def SendFile (name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send('ERROR')
sock.close()
def RetrFile (name, sock):
filename = sock.recv(1024)
data = sock.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
sock.send('OK')
f = open('new_' + filename, 'wb')
data = sock.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = sock.recv(1024)
totalRecieved += len(data)
f.write(data)
sock.close()
myHost = ''
myPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.bind((myHost, myPort))
s.listen(5)
print("Server Started.")
while True:
connection, address = s.accept()
print("Client Connection at:", address)
# u = threading.Thread(target=RetrFile, args=("retrThread", connection))
t = threading.Thread(target=SendFile, args=("sendThread", connection))
# u.start()
t.start()
s.close()
客戶端代碼
from socket import *
import sys
import os
servHost = ''
servPort = 7005
s = socket(AF_INET, SOCK_STREAM)
s.connect((servHost, servPort))
decision = raw_input("do you want to send or retrieve a file?(send/retrieve): ")
if decision == "retrieve" or decision == "Retrieve":
filename = raw_input("Filename of file you want to retrieve from server: ") # ask user for filename
if filename != "q":
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = raw_input("File Exists, " + str(filesize)+"Bytes, download?: Y/N -> ")
if message == "Y" or message == "y":
s.send('OK')
f = open('new_' + filename, 'wb')
data = s.recv(1024)
totalRecieved = len(data)
f.write(data)
while totalRecieved < filesize:
data = s.recv(1024)
totalRecieved += len(data)
f.write(data)
print("{0: .2f}".format((totalRecieved/float(filesize))*100)) + "% Done" # print % of download progress
print("Download Done!")
else:
print("File does not exist!")
s.close()
elif decision == "send" or decision == "Send":
filename = raw_input("Filename of file you want to send to server: ")
if filename != "q":
s.send(filename)
if os.path.isfile(filename):
s.send("EXISTS " + str(os.path.getsize(filename)))
userResponse = s.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
s.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
s.send(bytesToSend)
else:
s.send('ERROR')
s.close()
s.close()
我還是新的節目,所以這對我來說是相當艱難。總而言之,我只是想弄清楚如何發送和接收文件,而不必在我的SERVER CODE中註釋掉底線。
請和謝謝!
這不是FTP,對不對?這是你的自定義協議。 –
對不起,如果我的術語關閉,可能不是FTP。 –
如果您有兩個不同線程試圖同時從同一個套接字接收數據,您會發生什麼? – immibis