简体   繁体   English

在无协程函数中,如何从Tornado TCP的协程函数中获取返回值?

[英]In a no-coroutine function, how do you get a return value from coroutine function of Tornado TCP?

I wrote 3 sections of code with Tornado TCP. 我用Tornado TCP编写了3部分代码。 I've encountered some difficulties. 我遇到了一些困难。

My code is following: 我的代码如下:

client.py client.py

'''tcp client'''


from socket import socket, AF_INET, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
s.connect(('localhost', 20000))
resp = s.recv(8192)
print('Response:', resp)
s.send(b'Hello\n')
s.close()

server.py server.py

'''tcp server'''

#! /usr/bin/env python
#coding=utf-8

from tornado.tcpserver import TCPServer
from tornado.ioloop import IOLoop
from tornado.gen import *

clientDict=dict()        #save infomation of client

class TcpConnection(object):
    def __init__(self,stream,address):
        self._stream=stream
        self._address=address
        self._stream.set_close_callback(self.on_close)

    @coroutine
    def send_messages(self):
        yield self.send_message(b'world \n')
        response = yield self.read_message()

        return response


    def read_message(self):
        return self._stream.read_until(b'\n')

    def send_message(self,data):
        return self._stream.write(data)

    def on_close(self):
        global clientDict
        clientDict.pop(self._address)
        print("the monitored %d has left",self._address)

class MonitorServer(TCPServer):
    @coroutine
    def handle_stream(self,stream,address):
        global clientDict
        print("new connection",address,stream)
        clientDict.setdefault(address, TcpConnection(stream,address))



if __name__=='__main__':
    print('server start .....')
    server=MonitorServer()
    server.listen(20000)
    IOLoop.instance().start()

main.py main.py

import time
from threading import Thread
import copy
from server import *

def watchClient():
    '''call the "send" function when a new client connect''

    global clientDict
    print('start watch')
    lastClientList=list()
    while True:
        currentClientList=copy.deepcopy([key for key in clientDict.keys()])
        difference=list(set(currentClientList).difference(set(lastClientList)))

        if len(difference)>0:
            send(difference)
            lastClientList=copy.deepcopy(currentClientList)
            time.sleep(5)
        else:
            time.sleep(5)
            continue

def send(addressList):
    '''send message to a new client and get response'''
    global clientDict
    for address in addressList:
        response=clientDict[address].send_messages()
        print(address," response :",response)

def listen():
    server=MonitorServer()
    server.listen(20000)
    IOLoop.instance().start()


if __name__=='__main__':
    listenThread=Thread(target=listen)
    watchThead=Thread(target=watchClient)
    watchThead.start()
    listenThread.start()

I want to get the "print information" when the main.py is run--- address,response:b'hello\\n' 我想在main.py运行时获取“打印信息” --- 地址,响应:b'hello \\ n'

But in fact I get the "print information" as ---- 但实际上我得到的“打印信息”为----

('127.0.0.1', 41233)  response :<tornado.concurrent.Future object at 0x7f2894d30518>

It can't return the b'hello\\n' . 它无法返回b'hello \\ n'

Then I guess it can't get the response reasonably in the no-coroutine function( def send(addressList) ) from the coroutine function( @coroutine def send_messages(self) ). 然后我猜想它不能从协程函数( @coroutine def send_messages(self) )在no-协程函数( def send(addressList) )中合理地获得响应。

How to solve this? 如何解决呢?

By the way, I want to know how to make the clientDict to be a property of the class MonitorServer ,not a global property. 顺便说一句,我想知道如何使clientDict成为MonitorServer类的属性,而不是全局属性。 Please help me! 请帮我! Thank you. 谢谢。

In general, anything that calls a coroutine should be a coroutine itself. 通常,任何称为协程的东西都应该是协程本身。 Mixing threads and coroutines can be very tricky; 混合线程和协程可能非常棘手。 most coroutine-based code is deliberately not thread-safe. 大多数基于协程的代码故意不是线程安全的。

The correct way to call a coroutine from a non-coroutine function on a different thread is something like this: 不同线程上的非协程函数调用协程的正确方法是这样的:

def call_coro_from_thread(f, *args, **kwargs):
    q = queue.Queue()
    def wrapper():
        fut = f(*args, **kwargs)
        fut.add_done_callback(q.put)
    IOLoop.instance().add_callback(wrapper)
    fut = q.get()
    return fut.result()

IOLoop.add_callback is necessary to safely transfer control to the IOLoop thread, and then the Queue is used to transfer the result back. IOLoop.add_callback是将控制安全地传输到IOLoop线程所必需的,然后使用Queue来将结果传输回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM