最近在了解 websocket,但是发现死活不能保持长连接,用 tornado 实现了一个 server:
# coding=utf8
from tornado.websocket import WebSocketHandler
from tornado.web import asynchronous, Application
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.gen import coroutine, sleep
class WSHandler(WebSocketHandler):
@asynchronous
def open(self, *args, **kwargs):
print '{0} connected'.format(self.request.remote_ip)
@coroutine
def on_message(self, message):
if message:
if message:
yield sleep(5)
self.write_message("it\'s is done")
def on_close(self):
print 'client is exit'
def main():
app = Application([(r'/', WSHandler)],
static_path='static')
server = HTTPServer(app)
server.listen(8088)
IOLoop.instance().start()
if __name__ == '__main__':
main()
客户端代码:
import socket
from websocket import create_connection
import websocket
while 1:
ws = create_connection("ws://localhost:8088/", timeout=5)
if ws.connected:
ws.send('am coming', opcode=websocket.ABNF.OPCODE_TEXT)
print ws.recv()
# ws.close()
当 client 调用recv()
函数后就退出了,有什么办法可以做到一直保持链接,然后客户端得到消息可以正常处理
1
Kilerd 2017-08-07 08:15:39 +08:00 via iPhone
心跳包试试
|
2
CoX 2017-08-07 08:25:02 +08:00 via iPhone
逻辑没写对吧,每次循环都创建新的连接。建议看看官方给的例子。
|
3
CoX 2017-08-07 08:26:37 +08:00 via iPhone
把 if 改成 while,下面再 sleep 1 秒,试试看。
|
4
mooncakejs 2017-08-07 08:32:15 +08:00 via iPhone
改用 socketio
|
5
dangyuluo 2017-08-07 09:25:57 +08:00 1
create_connection 不能自动复用已有链接吧?你这每次 while 都新建一个链接
|
6
keakon 2017-08-07 11:13:25 +08:00 1
create_connection 放循环外去啊…
|