2016-09-23 20 views
2

收到到目前为止,我可以将文件发送到我的“文件服务器”,并从那里以及检索文件。但我不能同时做这两件事。我必须评论其他线程的其中一个工作。正如你将在我的代码中看到的那样。试图建立一个原油发送/ 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中注释掉底线。

请和谢谢!

+0

这不是FTP,对不对?这是你的自定义协议。 –

+0

对不起,如果我的术语关闭,可能不是FTP。 –

+0

如果您有两个不同线程试图同时从同一个套接字接收数据,您会发生什么? – immibis

回答

0

刚才if语句发送真或假,这将决定执行哪个线程。

0

在服务器端,你想用你的两个线程t和u相同的连接。

我想,如果你听了服务器在您while True:循环另一个连接,它可能工作你开始你的第一个线程之后。

我总是使用更高层次的socketserver模块(Python Doc on socketserver),它本身也支持线程处理。我建议检查一下!

顺便说一句,因为你做了很多的if (x == 'r' or x == 'R'):你可以只是做if x.lower() == 'r'

+0

所以看起来我能够通过创建一个新的连接来使两个线程都能正常工作,正如人们在这里所建议的那样。无论如何,使我的线程可以采取第二或第一个连接值? –

+0

我不知道我理解你的问题,但我猜你希望每个线程都能够检索和发送?在这种情况下,我认为将'SendFile'和'RetrFile'函数统一到* one *函数就足够了,并且用'threading.Thread(target = UnifiedFunction)'将它们提供给两个线程。因此,将两个函数重写为一个,在'filename = sock.recv(1024)'后检查文件是否存在,如果存在,发送它,如果不存在,继续'data = sock.recv(1024) '并检索它。 – krork