WebSocket的工作流程:浏览器通过JavaScript向服务端发出建立WebSocket连接的请求,在WebSocket连接建立成功后,客户端和服务端就可以通过 TCP连接传输数据。因为WebSocket连接本质上是TCP连接,不需要每次传输都带上重复的头部数据,所以它的数据传输量比轮询和Comet技术小很多。
接下来介绍一个执行Linux服务器备份脚本的案例:
第一步:安装websocket,在Pycharm中很容易,只需要搜索dwebsocket然后安装就好了;
第二步:创建一个Django项目,在templates下创建一个index.html页面,代码如下:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>游戏运维平台</title>
<script src="/static/jquery-1.12.4.js"></script>
<script type="text/javascript">//<![CDATA[
$(function () {
$('#backup_all').click(function () {
var socket = new WebSocket("ws://" + window.location.host + "/echo_once/");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
socket.send($('#backup_all').val());//发送数据到服务端
};
socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印服务端返回的数据
$('#messagecontainer').prepend('<p><pre>' + e.data + '</pre></p>');
$('#messagecontainer').prepend('<hr />');
};
});
});
</script>
</head>
<body>
<br>
<button style="margin: 20px;height: 40px;background-color: #00ff00;" type="button" id="backup_all" value="backup_all">
执行全平台备份脚本
</button>
<h3 style="margin: 20px;">脚本执行结果:</h3>
<div id="messagecontainer" style="margin: 20px;">
</div>
<hr/>
</body>
</html>
PS:jquery没有的话自己下一个放在static目录下(如果有static目录,记得在Django的settings中设置static路径),也可以使用在线的,网上搜一下很多的。这段代码就是提供一个按钮发送他的值到Django服务器,然后会在服务器中根据所传的值进行操作。
第三步:配置urls:
from websocket import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^echo_once', views.echo_once),
]
第四步:实现views中的视图逻辑处理:
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse
import paramiko
def exec_command(comm):
hostname = '你要连接的Linux服务器IP'
username = '登陆的Linux账号'
password = '登陆的Linux账号密码'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(comm)
result = stdout.read()
ssh.close()
return result
@accept_websocket
def echo_once(request):
if not request.is_websocket(): # 判断是不是websocket连接
try: # 如果是普通的http方法
message = request.GET['message']
return HttpResponse(message)
except:
return render(request, 'index.html')
else:
for message in request.websocket:
message = message.decode('utf-8')
if message == 'backup_all':#这里根据web页面获取的值进行对应的操作
command = 'sh test.sh'#这里是要执行的命令或者脚本,我这里写死了,完全可以通过web页面获取命令,然后传到这里
request.websocket.send(exec_command(command)) # 发送消息到客户端
else:
request.websocket.send('小样儿,没权限!!!'.encode('utf-8'))
视图函数也比较简单,就是根据前端按钮的value判断,执行脚本操作,使用的是paramiko连接Linux执行命令,最后把结果通过websocket发送到前端页面,进行展示。
这是最后的运行结果:
这是项目工程结构:
最后列出websocket的一些方法和属性:
一些方法和属性
1.request.is_websocket()
如果是个websocket请求返回True,如果是个普通的http请求返回False,可以用这个方法区分它们。
2.request.websocket
在一个websocket请求建立之后,这个请求将会有一个websocket属性,用来给客户端提供一个简单的api通讯,如果request.is_websocket()是False,这个属性将是None。
3.WebSocket.wait()
返回一个客户端发送的信息,在客户端关闭连接之前他不会返回任何值,这种情况下,方法将返回None
4.WebSocket.read()
如果没有从客户端接收到新的消息,read方法会返回一个新的消息,如果没有,就不返回。这是一个替代wait的非阻塞方法
5.WebSocket.count_messages()
返回消息队列数量
6.WebSocket.has_messages()
如果有新消息返回True,否则返回False
7.WebSocket.send(message)
向客户端发送消息
8.WebSocket.iter()
websocket迭代器