pywss是一种类似Flask开发的WebSocket-Server服务端框架,适用python3.X
一、安装
pip install pywss
二、使用
from pywss import Pyws, route
@route('/websocket')
def my_websocket(request, data):
print(‘客户端发来数据:%s’ % data)
return data + ' - data from pywss'
if __name__ == '__main__':
ws = Pyws(__name__, address='127.0.0.1', port=8888)
ws.serve_forever()
html:
<!DOCTYPE html>
<html>
<head>
<title>django-websocket</title>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">//<![CDATA[
$(function () {
$('#connect_websocket').click(function () {
if (window.s) {
window.s.close()
}
/*创建socket连接*/
var socket = new WebSocket("ws://127.0.0.1:8888/websocket");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
};
socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印出服务端返回过来的数据
$('#messagecontainer').prepend('<p>' + e.data + '</p>');
};
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
window.s = socket;
});
$('#send_message').click(function () {
//如果未连接到websocket
if (!window.s) {
alert("websocket未连接.");
} else {
window.s.send($('#message').val());//通过websocket发送数据
}
});
$('#close_websocket').click(function () {
if (window.s) {
window.s.close();//关闭websocket
console.log('websocket已关闭');
}
});
});
//]]></script>
</head>
<body>
<br>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" id="connect_websocket">连接 websocket</button>
<button type="button" id="send_message">发送 message</button>
<button type="button" id="close_websocket">关闭 websocket</button>
<h1>Received Messages</h1>
<div id="messagecontainer">
</div>
</body>
</html>