异步,多台计算机和大数据文件

时间:2018-06-22 10:52:29

标签: python asynchronous

希望将大文件从多台计算机发送到单台计算机。在寻找潜在的解决方案之后,我找到了asyncore模块。一个问题是我不知道如何设置发送大文件的代码。

服务器代码

import asyncore, socket

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(('', port))
        self.listen(1)

    def handle_accept(self):
        # when we get a client connection start a dispatcher for that
        # client
        socket, address = self.accept()
        print 'Connection by', address
        EchoHandler(socket)

class EchoHandler(asyncore.dispatcher_with_send):
    # dispatcher_with_send extends the basic dispatcher to have an output
    # buffer that it writes whenever there's content
    def handle_read(self):
        self.out_buffer = self.recv(1024)
        if not self.out_buffer:
            self.close()

s = Server('', 5007)
asyncore.loop()

客户代码

import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, message):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.out_buffer = message

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'Received', self.recv(1024)
        self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

这是Richard Jones创建的示例,显示了基本的服务器客户端连接

我的一部分想在其中抛出一个while循环以大块形式发送大型数据文件,但是我不知道在发送1条消息后它是否真正起作用,它将关闭连接。我实际上不知道该怎么写。

客户代码

import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, target):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.File = open(target,"wb"); 
        self.out_buffer = self.File.read(1024)

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'Received', self.recv(1024)
        self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

0 个答案:

没有答案