python实现简易的websocket功能

[复制链接]
查看1717 | 回复4 | 2022-2-4 20:34:23 | 显示全部楼层 |阅读模式
服务端采用websocket实现

性能会不怎么好

后期将采用高性能框架进行开发



python服务端:

  1. # 打开终端输入:pip install websockets 下载模块即可

  2. import asyncio
  3. import websockets


  4. # 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
  5. async def check_permit(websocket):
  6.     while True:
  7.         name = await websocket.recv()
  8.         print("服务端收到的信息:" + name)
  9.         greeting = "服务端处理完毕了"
  10.         await websocket.send(greeting)


  11. # 服务器端主逻辑,可多加函数也可设置权限访问
  12. # websocket和path是该函数被回调时自动传过来的,不需要自己传
  13. async def main_socket(websocket, path):
  14.     await check_permit(websocket)


  15. start_server = websockets.serve(main_socket, '0.0.0.0', 5000)
  16. asyncio.get_event_loop().run_until_complete(start_server)
  17. asyncio.get_event_loop().run_forever()
复制代码


懒人客户端:

  1. --本代码是直接复制 打开一个websocket连接 ,修改IP和端口即可
  2. local ws = nil

  3. function wLog(text)
  4.         print(text)
  5.         toast(text,0,0,20)
  6. end

  7. function onOpened(handle)
  8.         ws = handle
  9.         print("连接上服务器")
  10. end

  11. function reConnect()
  12.         sleep(2000)
  13.         wLog("断开连接,3秒后重连")
  14.         setTimer(function()
  15.                 ws = nil
  16.                 startWebSocket("ws://192.168.200.108:5000",
  17.                 onOpened,onClosed,onError,onRecv)
  18.         end,3000)
  19. end

  20. function onClosed(handle)
  21.         reConnect()
  22. end

  23. function onError(handle)
  24.         reConnect()
  25. end

  26. function onRecv(handle,message)
  27.         local text = "消息:"..message
  28.         wLog(text)
  29. end

  30. local handle = startWebSocket("ws://192.168.200.108:5000",
  31. onOpened,onClosed,onError,onRecv)


  32. if handle ~= nil then
  33.         local tick = 1
  34.         while true do
  35.                 if ws ~= nil then
  36.                         sendWebSocket(ws,string.format("hello:%d",tick))
  37.                         tick = tick + 1
  38.                 end
  39.                 sleep(100)
  40.         end
  41. end
复制代码

回复

使用道具 举报

教主 | 2022-2-4 20:38:28 | 显示全部楼层
打错了字,是采用了websockets模块开发
回复

使用道具 举报

squallx | 2022-2-25 20:38:21 | 显示全部楼层
websocket能运行脚本中的自定义函数吗
回复

使用道具 举报

152324093 | 2022-5-4 16:33:56 | 显示全部楼层
回复

使用道具 举报

152324093 | 2022-5-4 16:34:42 | 显示全部楼层
项目也就  几百台 设备  要撒性能  都不是考虑范围内的事情
再大的工作室  也就  几百台    有多少人 几千台的
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1

主题

2

帖子

12

积分

新手上路

Rank: 1

积分
12
QQ