websocket 初步使用经验(python)
-
想实现网页前端和后端的数据同步交互,就有必要使用 websocket 的方式进行通信。
-
python websocket github 地址:git@github.com:Aplexchenfl/python-websocket-server.git
-
下载之后:
ECM_5412@chenfl:/var/www/html$ ls
client.html README.md server.py setup.py tests websocket_server
-
其中,服务端的代码如下:
vim server.py
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))
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()
// 通过 python3 启动这个客户端
python3 server.py
-
客户端代码如下:
<html>
<head>
<title>Simple client</title>
<script type="text/javascript">
var ws;
function init() {
// 获取服务端ip
var ip_addr = document.location.hostname;
window.WebSocket = window.WebSocket || window.MozWebSocket;
ws = new WebSocket('ws://' + ip_addr +':9001'); // 申请新的客户端
// Connect to Web Socket
//ws = new WebSocket("ws://localhost:9001/");
// Set event handlers.
ws.onopen = function() {
output("onopen");
};
ws.onmessage = function(e) {
// e.data contains received string.
output("onmessage: " + e.data);
};
ws.onclose = function() {
output("onclose");
};
ws.onerror = function(e) {
output("onerror");
console.log(e)
};
}
function onSubmit() {
var input = document.getElementById("input");
// You can send message to the Web Socket using ws.send.
ws.send(input.value);
output("send: " + input.value);
input.value = "";
input.focus();
}
function onCloseClick() {
ws.close();
}
function output(str) {
var log = document.getElementById("log");
var escaped = str.replace(/&/, "&").replace(/</, "<").
replace(/>/, ">").replace(/"/, """); // "
log.innerHTML = escaped + "<br>" + log.innerHTML;
}
</script>
</head>
<body onload="init();">
<form onsubmit="onSubmit(); return false;">
<input type="text" id="input">
<input type="submit" value="Send">
<button onclick="onCloseClick(); return false;">close</button>
</form>
<div id="log"></div>
</body>
</html>
// 通过网页启动客户端。
Read The Fucking Source Code