connecting python to javascript for two-direction communication

前端 未结 2 1865
广开言路
广开言路 2020-12-29 00:40

I would like to serve queries from a javascript code by python. But I am not experienced in this field at all. What I would like to build is something like this:

2条回答
  •  被撕碎了的回忆
    2020-12-29 01:10

    An example with Web Socket that i have used to transfer image to a web server and stream my screen.

    stream.html

    
    
    
    
        
    Stream

    request.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;
        }
    }
    

    server.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()
    

    You will need autobahn (you can install it with pip install autobahn)

提交回复
热议问题