python3 寫一個簡單的websocket程序(轉)

原貼:https://segmentfault.com/q/1010000009284816?_ea=1883181python

也是找了很久web

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# install ws4py
# pip install ws4py
# easy_install ws4py
from ws4py.client.threadedclient import WebSocketClient


class DummyClient(WebSocketClient):
    def opened(self):
        self.send("www.baidu.com")

    def closed(self, code, reason=None):
        print("Closed down", code, reason)

    def received_message(self, m):
        print("recv:",m)


if __name__ == '__main__':
    try:
        ws = DummyClient('ws://localhost:9002/websocket', protocols=['chat'])
        ws.connect()
        ws.send("my test...")
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()
相關文章
相關標籤/搜索