python 模拟简易版websocket的客户端

第一步:

下载websocket-client模块

pip install websocket-client

 

第二步:

1、导包

from websocket import create_connection

2、指南

生成websocket对象:

ws = create.connection("ws://127.0.0.1:8888/webscoket")

向服务端发送数据:

ws.send()

接收来自服务端的数据:

ws.recv()

关闭当前连接:

ws.close()

第三步:

小试牛刀

from websocket import create_connection
import logging


class gateway_client:
    def __init__(self, url):
        self.url = url

    def connect(self):
        url = self.url
        try:
            ws = create_connection(url=url)
            logging.info("Connect to websocketserver successfully!")
            return ws
        except:
            logging.info("Failed to connect to websocketserver!")
            return ""

    def send(self, wsObj, message):
        if not wsObj or not message:
            logging.error("Parameter Error!")
            return "NO"
        try:
            wsObj.send(message)
        except:
            logging.error("Failed to send message to websocketserver!")
            return

    def recv(self, wsObj):
        while 1:
            res = wsObj.recv()
            print(res)

    def main(self):
        ws = self.connect()
        if ws != "":
            self.recv(ws)


if __name__ == '__main__':
    client = gateway_client("ws://127.0.0.1:8888/websocket")
    client.main()

一个简单的websocket客户端就完成了,想做的功能可以自主去开发。

你可能感兴趣的:(Python高级)