/*************************************************************************
* python-websocket-server hacking
* 说明:
* 跟一下python-websocket-server怎么使用,这个lib还算是目前想用的。
*
* 2017-10-6 深圳 南山平山村 曾剑锋
************************************************************************/ 一、参考文档:
https://github.com/ZengjfOS/python-websocket-server 二、client.html
<html>
<head>
<title>Simple client</title> <script type="text/javascript"> var ws; function init() { // Connect to Web Socket
ws = new WebSocket("ws://localhost:9001/"); // Set event handlers.
// 连接WebSocket服务器成功,打开成功
ws.onopen = function() {
output("onopen");
}; // 收到WebSocket服务器数据
ws.onmessage = function(e) {
// e.data contains received string.
output("onmessage: " + e.data);
}; // 关闭WebSocket连接
ws.onclose = function() {
output("onclose");
}; // WebSocket连接出现错误
ws.onerror = function(e) {
output("onerror");
console.log(e)
}; } // 将当前文本框中的内容发送到WebSocket
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();
} // 关闭WebSocket连接
function onCloseClick() {
ws.close();
} // 在界面上显示接收到的数据,将替换掉一些需要转义的字符
function output(str) {
var log = document.getElementById("log");
var escaped = str.replace(/&/, "&amp;").replace(/</, "&lt;").
replace(/>/, "&gt;").replace(/"/, "&quot;"); // "
log.innerHTML = escaped + "<br>" + log.innerHTML;
} </script>
</head> <!-- 文档加载完毕之后,会调用init函数进行处理 -->
<body onload="init();">
<!-- 点击submit之后,调用onSubmit函数 -->
<form onsubmit="onSubmit(); return false;">
<!-- 发送数据的输入框 -->
<input type="text" id="input">
<input type="submit" value="Send">
<!-- 点击关闭按钮关闭WebSocket连接 -->
<button onclick="onCloseClick(); return false;">close</button>
</form>
<!-- 显示发送、接收到数据 -->
<div id="log"></div>
</body>
</html> 三、server.py
# 加载WebsocketServer模块
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) > :
message = message[:]+'..'
print("Client(%d) said: %s" % (client['id'], message)) # 发送给所有的连接
server.send_message_to_all(message) # Server Port
PORT=
# 创建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()
05-22 14:30