python - 尝试在 python 中通过 TCP 创建粗略的发送/接收

标签 python tcp

到目前为止,我可以将文件发送到我的“文件服务器”并从那里检索文件。但我不能同时做这两件事。我必须注释掉其他线程之一才能使它们工作。正如您将在我的代码中看到的那样。

服务器代码

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

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

拜托,谢谢!

最佳答案

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

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

我总是使用更高级的 socketserver 模块 ( Python Doc on socketserver ),它也原生支持线程。我建议检查一下!

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

关于python - 尝试在 python 中通过 TCP 创建粗略的发送/接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39654060/

相关文章:

python - 如何阻止 pygame Sprite 离开 'tail'

python - ffmpeg-python 中的图像叠加

python - Pytorch如何像for循环一样堆叠张量

c++ - 接收来自服务器的传入流量

tcp - 使用 OTP 原理的非阻塞 TCP 服务器

TCP 文件传输窗口大小

python - 如何使用 python 中的 csv 模块导入分隔符不规则的文件?

具有共享变量(值)的 Python 多处理 Pool.apply_async

TCP/RTMP 握手

c# - 从 UWP 获取 TCP 服务器上的实时数据(更新)