尝试在python中通过TCP创建原始发送/接收

时间:2016-09-23 06:32:35

标签: python tcp

到目前为止,我可以将文件发送到我的" fileserver"并从那里检索文件。但我无法同时做到这两点。我必须注释掉其中一个线程才能使它们工作。正如您将在我的代码中看到的那样。

服务器代码

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()

我还是编程新手,所以对我来说这很难。总而言之,我只想弄清楚如何发送和接收文件而不必在我的服务器代码中注释掉底部线程。

请,谢谢!

2 个答案:

答案 0 :(得分:0)

在服务器端,您尝试为两个线程t和u使用相同的连接。

我认为如果您在启动第一个线程后在服务器上的while True:循环中侦听了另一个连接,它可能会有效。

我总是使用更高级的socketserver模块(Python Doc on socketserver),它本身也支持线程。我建议你看一下!

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

答案 1 :(得分:0)

刚刚发出一个if语句发送一个True或False,它将决定执行哪个线程。

相关问题