javascript 将python连接到javascript进行双向通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18233433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:09:07  来源:igfitidea点击:

connecting python to javascript for two-direction communication

javascriptpythonjsonconnectionrequest

提问by gen

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:

我想通过 python 提供来自 javascript 代码的查询。但我在这个领域完全没有经验。我想构建的是这样的:

1. request.js:

1. request.js

open_connection('server.py');
for (var i=0; i<10; i++)
    document.write(request_next_number());
close_connection('server.py')

2. server.py

2.服务器.py

x = 0
while connected:
    if request:
        send(x)
        x = x + 1

I heard about JSON, but don't know if I should use it. (?)

我听说过 JSON,但不知道我是否应该使用它。(?)

Could you please give me some code examples or guides how to implement the two files above?

你能给我一些代码示例或指导如何实现上面的两个文件吗?

回答by xlharambe

What you need is a socket server on the pythonend and a client/request server on the javascript end.

您需要的是python末端的套接字服务器和 javascript 末端的客户端/请求服务器。

For the python server side, refer to SocketServer, (example taken from there as well), one thing you have to make sure is to have the socket go past NAT(possibly port forwarding). One other alternative is Twistedwhich is a very powerful framework, i believe it has functionality to send data through NAT.

对于 python 服务器端,请参阅SocketServer, (示例也取自那里),您必须确保的一件事是让套接字通过NAT(可能是端口转发)。另一种选择是Twisted它是一个非常强大的框架,我相信它具有通过NAT.

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

On the JavaScriptthere are many frameworks that allow socket connections, here are a few

JavaScript有很多的框架,允许套接字连接,这里有几个

Example:

例子:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Example:

例子:

var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

Example:

例子:

_jssocket.setCallBack(event, callback);
_jssocket.connect(ip,port);
_jssocket.write(message);
_jssocket.disconnect();

Hope this help!

希望这有帮助!

回答by Etienne Prothon

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

一个 Web Socket 示例,我曾用它将图像传输到 Web 服务器并流式传输我的屏幕。

stream.html

流.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>

request.js

请求.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

服务器.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)

您将需要高速公路(您可以使用 安装它pip install autobahn