Python 通过套接字发送文件

Python sending files over socket

我想做一个文件调度程序,服务器加载文件列表,然后根据每个客户端请求一个一个地发送它们。 想法是在 5 个服务器之间分配许多文件的处理。

如何为每个客户端连接调用 ClientThread class?

脚本只被编程为向每个客户端请求发送相同的文件,我想要的是从每个客户端请求中的文件列表发送不同的文件。

Server.py

import socket
from threading import Thread
from socketserver import ThreadingMixIn

TCP_IP = '10.30.16.28'
TCP_PORT = 1006
BUFFER_SIZE = 1024

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='log.VW.20170214a.log'
        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 = []

with open("list.txt") as x: #File containing files list
    lines=x.read().splitlines()
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()

Client.py

import socket

TCP_IP = '10.30.16.28'
TCP_PORT = 1006
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
with open('received_file', 'wb') as f:
    print('file opened')
    while True:
        data = s.recv(BUFFER_SIZE)
        if not data:
            f.close()
            print('file close()')
            break
    f.write(data)

print('Successfully get the file')
s.close()
print('connection closed')

我看不出这与线程或端口或类似的东西有什么关系。改变这个:

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

def run(self):
    f = open(self.fname,'rb')

当你发球时:

with open("list.txt") as x: #File containing files list
    lines=iter(x.read().splitlines())

最后:

newthread = ClientThread(ip,port,conn,lines.next().strip())

lines.next() 完成后会抛出 StopIteration 异常,所以你必须处理它。