推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SlipStupig
V2EX  ›  Python

Python websocket-client 如何保持长连接呢?

  •  
  •   SlipStupig · Aug 7, 2017 · 7214 views
    This topic created in 3234 days ago, the information mentioned may be changed or developed.

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

    6 replies    2017-08-07 11:13:25 +08:00
    Kilerd
        1
    Kilerd  
       Aug 7, 2017 via iPhone
    心跳包试试
    CoX
        2
    CoX  
       Aug 7, 2017 via iPhone
    逻辑没写对吧,每次循环都创建新的连接。建议看看官方给的例子。
    CoX
        3
    CoX  
       Aug 7, 2017 via iPhone
    把 if 改成 while,下面再 sleep 1 秒,试试看。
    mooncakejs
        4
    mooncakejs  
       Aug 7, 2017 via iPhone
    改用 socketio
    dangyuluo
        5
    dangyuluo  
       Aug 7, 2017   ❤️ 1
    create_connection 不能自动复用已有链接吧?你这每次 while 都新建一个链接
    keakon
        6
    keakon  
       Aug 7, 2017   ❤️ 1
    create_connection 放循环外去啊…
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3329 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 12:04 · PVG 20:04 · LAX 05:04 · JFK 08:04
    ♥ Do have faith in what you're doing.