python websocket 心跳_Python websocket-client 如何保持长连接呢?

谷梁宁
2023-12-01

最近在了解 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()函数后就退出了,有什么办法可以做到一直保持链接,然后客户端得到消息可以正常处理

 类似资料: