如何在Python服务器脚本中添加用于接收文件的附加功能

时间:2019-04-24 18:47:54

标签: python python-3.x sockets client-server

我有以下脚本,一旦客户端将文件连接到客户端,该脚本就会发送。

我正在尝试添加一项功能,当客户端发回文件以能够接受文件时

TCP_IP = "0.0.0.0"
TCP_PORT = 9001
BUFFER_SIZE = 4096

class ClientThread(Thread):

    def __init__(self,ip,port,sock):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.sock = sock
        print( " New thread started for "+ip+":"+str(port))

    def run(self):
        filename='times.csv'

        f = open(filename,'rb')

        while True:
            l = f.read(BUFFER_SIZE)
            while (l):
                self.sock.send(l)

                l = f.read(BUFFER_SIZE)
            if not l:
                f.close()

                self.sock.close()
                break

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []

while True:
    tcpsock.listen(5)
    print("Waiting for incoming connections...")
    (conn, (ip,port)) = tcpsock.accept()
    print( 'Got connection from ', (ip,port))
    newthread = ClientThread(ip,port,conn)
    newthread.start()

    threads.append(newthread)

for t in threads:
    t.join()

如果我不关闭套接字连接,客户端将不发送文件。那我该怎么办呢?

谢谢

0 个答案:

没有答案