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"}
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Python实现WebSocket服务端客户端,可以使用Python websockets库。该库基于asyncio异步IO构建,提供了基于协程的API。 首先,你需要安装websockets库,可以使用pip命令进行安装:pip3 install websockets。 对于服务端实现,你可以创建一个Python文件,并引入websockets和asyncio模块。使用async关键字定义一个async函数,例如叫做handle_client,这个函数将处理客户端连接并处理接收到的消息。在函数内部,使用async with语句创建一个WebSocket服务器对象,传入服务器的地址和端口。然后,使用一个无限循环来等待并处理客户端连接。在循环中,使用await关键字接收客户端发送的消息,并根据需要进行处理。最后,使用await关键字向客户端发送消息。下面是一个简单的示例代码: ```python import asyncio import websockets async def handle_client(websocket, path): async for message in websocket: # 处理接收到的消息 # ... # 发送消息给客户端 response = "Hello, client!" await websocket.send(response) start_server = websockets.serve(handle_client, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() ``` 对于客户端实现,你可以创建一个Python文件,并引入websockets和asyncio模块。使用async关键字定义一个async函数,例如叫做connect_to_server,这个函数将连接到服务器并发送消息。在函数内部,使用async with语句创建一个WebSocket客户端对象,传入服务器的地址和端口。然后,使用await关键字向服务器发送消息,并等待服务器的响应。最后,打印接收到的消息。下面是一个简单的示例代码: ```python import asyncio import websockets async def connect_to_server(): async with websockets.connect('ws://localhost:8765') as websocket: message = "Hello, server!" await websocket.send(message) response = await websocket.recv() print(response) asyncio.get_event_loop().run_until_complete(connect_to_server()) ``` 需要注意的是,以上示例只是一个简单的示例,你可以根据自己的需求进行修改和扩展。另外,确保你的Python版本是大于等于3.6的版本,因为websockets库对于较低版本的Python可能会有兼容性问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值