簡體   English   中英

Python通過套接字發送文件

[英]Python sending files over socket

我想做一個文件調度程序,服務器將加載文件列表,然后與每個客戶端請求一一發送。 這個想法是在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')

我看不到這與線程或端口或類似的東西有什么關系。 更改此:

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異常,因此您必須處理該異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM