python 使用 websocket 以及 websocket_client 实现简单的客户端与服务端

项目需要,有时候使用websockets 进行client 向 server 端通讯。
因此,使用python 写了一个简单的WSClient 与 WSServer 进行通讯。


依赖的三方库

依赖的三方库为: websocket, websocket-client.

pip install websocket  
pip3 install websocket-client

注意,对于websocket-client 需要使用的是 pip3. 如果使用 pip 的话,会报错。


客户端:

#!/usr/bin/python
# -*- coding: UTF-8 -*-


import json
import time
from websocket import create_connection


class WSClient:
    def __init__(self, address):
        self.ws = create_connection(address)

    def send(self, params):
        print("Sending ...")
        self.ws.send(json.dumps(params))
        print("Sending Data: {}".format(params))
        print("Reeiving...")
        result = self.ws.recv()
        print("Received '{}'".format(result))

    def quit(self):
        self.ws.close()


t = str(time.time() * 1000).split(".")[0]


params1 = {
    "version": 1,
    "msgNo": t,
    "machNo": "U040119110001",
    "cmd": 1,
    "time": t
}

if __name__ == '__main__':

    address = "ws://127.0.0.1:1234/ws"

    # 初始化
    web_client = WSClient(address)
    web_client.send(params1)

    # 断开连接
    web_client.quit()
    print(r'send end')

服务器端:

#!/usr/bin/env python
# encoding: utf-8

import websockets
import asyncio

class WSserver():
    async def handle(self, websocket, path):
        recv_msg = await websocket.recv()
        print("i received %s" % recv_msg)
        await websocket.send('server send ok')

    def run(self):
        ser = websockets.serve(self.handle, "127.0.0.1", "1234")
        asyncio.get_event_loop().run_until_complete(ser)
        asyncio.get_event_loop().run_forever()


ws = WSserver()
ws.run()

结果

客户端控制台结果:

Sending ...
Sending Data: {'version': 1, 'msgNo': '1603119220873', 'machNo': 'U040119110001', 'cmd': 1, 'time': '1603119220873'}
Reeiving...
Received 'server send ok'
send end

服务器端结果

begin ...
i received {"version": 1, "msgNo": "1603119205864", "machNo": "U040119110001", "cmd": 1, "time": "1603119205864"}
i received {"version": 1, "msgNo": "1603119220873", "machNo": "U040119110001", "cmd": 1, "time": "1603119220873"}

你可能感兴趣的:(Python实用源码,VTK,网络通信,python,客户端,服务端,通讯,websocket)