Python通过套接字发送文件

时间:2017-06-14 15:40:23

标签: python python-3.x sockets tcp-ip

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

如何在每次客户端连接时调用ClientThread类?

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

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

1 个答案:

答案 0 :(得分:0)

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

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个异常,所以你必须处理它。