websocket
通常要实现C/S或者B/S架构的通讯时,会选择websocket通讯协议。websocket允许服务器主动给客户端发送消息,如果是在自动化控制做服务器的时候,可以考虑使用此协议。
服务端代码
首先得先安装 websocket-server库
具体使用方法请查看库源代码,以下代码实现一些基本功能。
import threading
from websocket_server import WebsocketServer
# Called for every client connecting (after handshake)
def new_client(client, server):
print("New client connected and was given id %d" % client['id'])
# 发送给所有的连接
server.send_message_to_all("Hey all, a new client has joined us")
t1 = threading.Thread(target = send_message_test, args = (server,'111111'))
t1.start()
# Called for every client disconnecting
def client_left(client, server):
print("Client(%d) disconnected" % client['id'])
# Called when a client sends a message
def message_received(client, server, message):
print(message)
if len(message) > 200:
message = message[:200]+'..'
print("Client(%d) said: %s" % (client['id'], message))
# 发送给所有的连接
server.send_message_to_all(message)
# 单独发给指定用户信息
# server.send_message(client,'用户编号'+str(client['id'])+':'+message)
def send_message_test(server, message):
for x in range(5):
server.send_message_to_all(message)
# Server Port
PORT=8000
# 创建Websocket Server
server = WebsocketServer(PORT)
# 有设备连接上了
server.set_fn_new_client(new_client)
# 断开连接
server.set_fn_client_left(client_left)
# 接收到信息
server.set_fn_message_received(message_received)
# 开始监听
server.run_forever()
客户端代码
需要安装websocket_client
具体使用方法请查看库源代码,以下代码实现一些基本功能。
import socket
import websocket
from websocket import create_connection,WebSocket
class websocket_labview():
def __init__(self):
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("ws://127.0.0.1:8000/",
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close)
self.ws.run_forever()
def on_message(self,message):
print('on_message: ',message)
def on_error(self,message):
print('on_error:',message)
def on_close(self,ws,message):
print('on_close:',message)
def on_open(self,ws,message):
pass
if __name__ == '__main__':
ws = websocket_labview()