python:3.9.x
-case( Function code module folder )
--OutputPower.py( Function code , Received client information , Judge to enter the corresponding function module )
-websocket(webSocket Server code , Mainly responsible for maintaining the connection 、 receive data 、 send data )
--server.py( Server code )
-app.py( Program entrance )
server.py
Features include :
1、 establish websocket Connect
2、 Receive client information
3、 Send client information
Here I use multithreading , The main idea is to think about the interaction between functional modules in the future
import asyncio
import websockets
import time
import json
import threading
# Function module
from case.OutputPower import OutputPower
# Store all the clients
Clients = []
class Server():
# A callback function that sends a message to the client
async def s(self,msg,websocket=None):
await self.sendMsg(msg,websocket)
# Request for different information , You can consider json Text
async def runCase(self,jsonMsg,websocket):
print('runCase')
# await OutputPower(jsonMsg,self.s,websocket)
op = OutputPower()
await op.run(jsonMsg,self.s,websocket)
# Each client link will enter a loop
async def echo(self,websocket, path):
Clients.append(websocket)
await websocket.send(json.dumps({"type": "handshake"}))
while True:
try:
recv_text = await websocket.recv()
message = "I got your message: {}".format(recv_text)
# Directly return the information received by the client
await websocket.send(message)
print(message)
# Analyze the current message json Format , Jump into function module analysis
await self.runCase(jsonMsg='',websocket=websocket)
except websockets.ConnectionClosed:
print("ConnectionClosed...", path) # Link broken
Clients.remove(websocket)
break
except websockets.InvalidState:
print("InvalidState...") # Invalid state
Clients.remove(websocket)
break
except Exception as e:
print(e)
Clients.remove(websocket)
break
# Send a message
async def sendMsg(self,msg,websocket):
print('sendMsg:',msg)
if websocket != None:
await websocket.send(msg)
else:
await self.broadcastMsg(msg)
# Group-sent message
async def broadcastMsg(self,msg):
for user in Clients:
await user.send(msg)
# Start the server
async def runServer(self):
async with websockets.serve(self.echo, 'localhost', 8888):
await asyncio.Future() # run forever
# Multithreading mode , Prevent blocking the main thread from doing other things
def WebSocketServer(self):
asyncio.run(self.runServer())
def startServer(self):
# Multithreaded startup , Otherwise it will be blocked
thread = threading.Thread(target=self.WebSocketServer)
thread.start()
thread.join()
print("go!!!")
Do business separation (OutputPower.py)
import asyncio
class OutputPower():
async def run(self,arg,s,websocket):
# Send message method , Separate and requesting clients send messages
await s('sssss', websocket)
# Group-sent message
await s(' get up hi')
(app.py)
from webSocket.server import Server
if __name__=='__main__':
s = Server()
s.startServer()
Find an online one directly websocket Conduct connection test , Such as http://www.websocket-test.com/
The result is shown in Fig. :
12
I got your message:12
sssss
get up hi
get up hi
get up hi
see :https://download.csdn.net/download/weixin_44635546/85645105