程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to quickly build a websocket server with Python?

編輯:Python

preparation

python:3.9.x

  • python rely on
    pip3 install asyncio
    pip3 install json
    pip3 install websockets
    pip3 install pyvisa
    pip3 install configparser

Directory structure

-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 )

Code

server.py
Features include :
1、 establish websocket Connect
2、 Receive client information
3、 Send client information

Server data processing module

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!!!")

Build functional modules

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')

Start the service

(app.py)


from webSocket.server import Server
if __name__=='__main__':
s = Server()
s.startServer()

test

Find an online one directly websocket Conduct connection test , Such as http://www.websocket-test.com/

The result is shown in Fig. :

  • The first client link
  • send out :12
  • Server return :I got your message:12
  • Continue to return to the function module :sssss
  • Return mass messages : get up hi
  • Return mass messages : get up hi
  • The second client link
  • Repeat the first client work , But the first client received one more : get up hi

Test source

see :https://download.csdn.net/download/weixin_44635546/85645105


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved