【发布时间】:2015-07-14 09:50:30
【问题描述】:
我用 Tornado TCP 编写了 3 段代码。我遇到了一些困难。
我的代码如下:
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
'''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
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()
我想获取main.py运行时的“打印信息”---address,response:b'hello\n'
但实际上我得到的“打印信息”为----
('127.0.0.1', 41233) response :<tornado.concurrent.Future object at 0x7f2894d30518>
它不能返回 b'hello\n'。
那我猜它无法从协程函数(@coroutine def send_messages(self))。
如何解决?
顺便说一句,我想知道如何使 clientDict 成为 class MonitorServer 的属性,而不是全局属性。 请帮我!谢谢。
【问题讨论】: