我是Python的新手,我试图解决的问题是有一个正在进行的websocket连接,它可以接受请求,在执行calc时等待一段时间,在准备好时返回结果,同时不会阻塞来自其他用户/客户端/连接的其他请求。我已经做到了这一点,它的工作相当不错,但想检查这是不是正确的解决方案。在这个特定的代码片段中,它们的关键部分是在打开时执行的操作:我关闭了另一个休眠线程。
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import time
import json
from tornado import gen
from concurrent.futures import ThreadPoolExecutor
from tornado.options import define, options, parse_command_line
define("port", default=8888, type=int)
thread_pool = ThreadPoolExecutor(2)
class WebSocketHandler(tornado.websocket.WebSocketHandler):
# Make this an asynchronous coroutine
@gen.coroutine
def on_message_coroutine(self, message):
self.write_message('Message:', message)
def worker_A(websocket, x):
time.sleep(1)
print('TICK', x)
pass
return x
print('scheduling and yielding')
for x in range(0, 30):
test = yield thread_pool.submit(worker_A, self, x)
self.write_message(json.dumps(test))
print('done yielding')
def open(self, *args):
print("New connection")
tornado.ioloop.IOLoop.current().spawn_callback(self.on_message_coroutine, 'New Msg')
def check_origin(self, origin):
return True
def on_message(self, message):
print("New message {}".format(message))
self.write_message("You sent me this, sending it back in upper: " + message.upper())
def on_close(self):
print("Connection closed")
app = tornado.web.Application([
(r'/ws/', WebSocketHandler),
])
if __name__ == '__main__':
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
以下是前端控制台上的输出。“新消息”位是指当websocket连续返回其他输出(滴答)时,我单击按钮时:
app.component.ts:17 Response from websocket: 11
app.component.ts:17 Response from websocket: 12
app.component.ts:17 Response from websocket: 13
app.component.ts:17 Response from websocket: 14
app.component.ts:24 new message from client to websocket: gotta be a string
app.component.ts:17 Response from websocket: You sent me this, sending it back in upper: "GOTTA BE A STRING"
app.component.ts:17 Response from websocket: 15
app.component.ts:17 Response from websocket: 16
app.component.ts:17 Response from websocket: 17
app.component.ts:24 new message from client to websocket: gotta be a string
app.component.ts:17 Response from websocket: You sent me this, sending it back in upper: "GOTTA BE A STRING"
app.component.ts:17 Response from websocket: 18
app.component.ts:17 Response from websocket: 19
app.component.ts:17 Response from websocket: 20
app.component.ts:17 Response from websocket: 21
https://stackoverflow.com/questions/50633359
复制相似问题