第二次通话失败

时间:2015-06-16 14:11:58

标签: python asynchronous call

我需要你的帮助。

此代码仅工作一次,第二个wget提供超时(附加文件)。

  

wget http://localhost:9090

#!/usr/bin/env python

import trollius as asyncio
from trollius import From
import os

class Client(asyncio.Protocol):

    def connection_made(self, transport):
        self.connected = True
        # save the transport
        self.transport = transport

    def data_received(self, data):
        # forward data to the server
        self.server_transport.write(data)

    def connection_lost(self, *args):
        self.connected = False

class Server(asyncio.Protocol):
    clients = {}

    def connection_made(self, transport):
        # save the transport
        self.transport = transport

    @asyncio.coroutine
    def send_data(self, data):
        # get a client by its peername
        peername, port = self.transport.get_extra_info('peername')
        client = self.clients.get(peername)
        # create a client if peername is not known or the client disconnect
        if client is None or not client.connected:
            protocol, client = yield From(loop.create_connection(Client, 'google.com', 80))
            client.server_transport = self.transport
            self.clients[peername] = client
        # forward data to the client
        client.transport.write(data)

    def data_received(self, data):
        # use a task so this is executed async
        asyncio.Task(self.send_data(data))

@asyncio.coroutine
def initialize(loop):
    # use a coroutine to use yield from and get the async result of
    # create_server
    server = yield From(loop.create_server(Server, '127.0.0.1', 9090))

loop = asyncio.get_event_loop()

# main task to initialize everything
asyncio.Task(initialize(loop))

# run
loop.run_forever()

有谁知道原因?

谢谢!

1 个答案:

答案 0 :(得分:0)

在asyncio中编写套接字服务器时,服务器中需要一个真正的“循环”。请注意,尽管有'sync'编码,但无限循环不会阻止执行。您需要在服务器中使用无限循环。有很多样本,我推荐websockets库样本!