正常http就够了,但是若是需要双向通信的话,websocket就会更加简单些。下面介绍python下的一些实践。
服务器端
选择 websocket-server,快速安装
pip install websocket-server
例子:
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")
# 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):
if len(message) > 200:
message = message[:200]+'..'
print("Client(%d) said: %s" % (client['id'], message))
server.send_message(client, "got your message")
PORT = 9001
server = WebsocketServer(PORT, '0.0.0.0')
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)
server.run_forever()
更多详情请访问: https://github.com/Pithikos/python-websocket-server
客户端
建议选择websocket-client,有多种创建方式,代码简洁。Github 2.3k star。可靠。
快速安装
pip install websocket-client
https://github.com/websocket-client/websocket-client
from websocket import create_connection
ws = create_connection("ws://10.26.137.129:9001/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
总结
对于python3.5以下,目前来看,当前的选择是更加实践。若是python3.5以上,可以试试