基于websocket实现多端即时通讯小示例,可以实现多个客户端的即时通讯.
python 源码需要先安装一下:
pip install SimpleWebSocketServer 第三方库
synchronizer.py 文件源码:
- import json
- from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
- wss = []
- class SimpleEcho(WebSocket):
- # 接收设备发送来的数据
- def handleMessage(self):
- if self.data is None:
- self.data = ''
- print(self.address,'发送的数据:',self.data)
- # 接收数据 广播给所以 连接设备
- for i in wss:
- i.sendMessage(json.dumps({'code':200,'msg':self.data},ensure_ascii=False))
- def handleConnected(self):
- # 客户端连接打印 ip:端口
- print(self.address, '设备连接成功')
- if not self in wss:
- wss.append(self)
- def handleClose(self):
- # 客户端关闭后打印
- print(self.address, '设备已断开')
- @staticmethod
- def run():
- print('websocket 服务器启动中...')
- server = SimpleWebSocketServer('0.0.0.0', 8000, SimpleEcho)
- server.serveforever()
- if __name__ == '__main__':
- SimpleEcho.run()
复制代码
多端同步器.lua 文件源码:
- --本代码是直接复制 打开一个websocket连接 ,修改IP和端口即可
- local ws = nil
- -- 服务器ip端口
- address = '192.168.0.101:8000'
- nodeTab = {
- 应用市场={bounds={l=786,t=275,r=1032,b=533},class="android.widget.TextView",text="华为应用市场"},
- 搜索={bounds={l=156,t=264,r=1008,b=384},class="android.widget.TextSwitcher",index="1",level="16"},
- 输入框={bounds={l=276,t=96,r=851,b=216},class="android.widget.EditText",index="1",level="13"}
- }
- function findNode(class,click,findName)
- nodeLib.updateNode()
- -- 找节点
- local ret = nodeLib.findOne(class,true)
- if ret ~= nil then
- -- 找到点击
- print('找到节点了')
- if click then
- nodeLib.click(ret)
- end
-
- end
- sleep(2000)
- -- 找到写入文字
- if findName then
-
- local ret1 = nodeLib.findOne(nodeTab['输入框'],true)
- nodeLib.setText(ret1,findName)
-
- end
-
- end
- function json(str)
-
- return jsonLib.decode(splitStr(str,"消息:")[2])
- end
- function wLog(text)
- print(text)
- toast(text,0,0,12)
-
- end
- function onOpened(handle)
- ws = handle
- print("连接上服务器")
- --sendWebSocket(ws,'服务器1')
-
- end
- function reConnect()
- sleep(2000)
- wLog("断开连接,3秒后重连")
- setTimer(function()
- ws = nil
- startWebSocket(string.format("ws://%s",address),
- onOpened,onClosed,onError,onRecv)
- end,3000)
- end
- function onClosed(handle)
- reConnect()
- end
- function onError(handle)
- reConnect()
- end
- function onRecv(handle,message)
- print('服务器返回数据:',message)
- wLog(message)
- -- 可在这里实现对应操作
- local res = jsonLib.decode(message)
-
- if res['code']==200 then
- --print('执行点击懒人精灵')
- --tap(659,377)
- toast(res['data'],0,0,30)
- local count = 1
- -- 接收websocket 数据后 执行对应操作
- findNode(nodeTab['应用市场'],true)
- sleep(3000)
- findNode(nodeTab['搜索'],true,'抖音')
-
-
- --findNode(nodeTab[],click,findName)
-
-
-
- end
- end
- local handle = startWebSocket(string.format("ws://%s",address),
- onOpened,onClosed,onError,onRecv)
- if handle ~= nil then
-
- while true do
- --[===[local x=-1 y=-1
- ret,x,y = findPic(267,283,582,526,"雷电.png","101010",0,0.98)
- print(ret,x,y)
- if x >= 1 and y >= 1 and sendData ~= '准备' then
- sendWebSocket(ws,'服务器1&准备')
- sendData = '准备'
- end]===]
- sleep(1000)
- end
-
-
- end
复制代码 运行结果图片:
|