我用来将图像传输到 Web 服务器并流式传输我的屏幕的 Web Socket 示例。
流.html
<!DOCTYPE HTML>
<meta charset = utf-8>
<html>
<header>
<title>Stream</title>
<script type="text/javascript" src="js/request.js"></script>
</header>
<body onload="doLoad()">
<div id="canvasWrapper">
<canvas id="display"></canvas>
</div>
</body>
</html>
请求.js
var disp;
var dispCtx;
var im;
var ws;
function doLoad() {
disp = document.getElementById("display");
dispCtx = disp.getContext("2d");
im = new Image();
im.onload = function() {
disp.setAttribute("width", im.width);
disp.setAttribute("height", im.height);
dispCtx.drawImage(this, 0, 0);
};
im.src = "img/img_not_found.png";
ws = new WebSocket("ws://127.0.0.1:50007");
ws.onmessage = function (evt) {
im.src = "data:image/png;base64," + evt.data;
}
}
服务器.py
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
import base64
import sys
from twisted.python import log
from twisted.internet import reactor
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def hello():
with open("/var/www/html/img/image.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
self.sendMessage(encoded_string.encode('utf8'))
self.factory.reactor.callLater(0.2, hello)
# start sending messages every 20ms ..
hello()
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {} bytes".format(len(payload)))
else:
print("Text message received: {}".format(payload.decode('utf8')))
# echo back message verbatim
self.sendMessage(payload, isBinary)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {}".format(reason))
if __name__ == '__main__':
log.startLogging(sys.stdout)
factory = WebSocketServerFactory(u"ws://127.0.0.1:50007")
factory.protocol = MyServerProtocol
# factory.setProtocolOptions(maxConnections=2)
# note to self: if using putChild, the child must be bytes...
reactor.listenTCP(50007, factory)
reactor.run()
您将需要高速公路(您可以安装它pip install autobahn
)