javascript - 连接 python 和 javascript 进行双向通信

标签 javascript python json connection request

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

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

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

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

您能给我一些代码示例或指南如何实现上述两个文件吗?

最佳答案

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

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

JavaScript上有很多允许套接字连接的框架,这里有一些

示例:

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

示例:

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

示例:

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

希望这有帮助!

关于javascript - 连接 python 和 javascript 进行双向通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233433/

相关文章:

javascript - `` 模板语法-优雅降级

javascript - 与背景图片一起定位时链接不起作用?

python - 比较日期字段的年月是否大于

python - 将二维值数组拆分为 X 和 y 数据集

php - 类型错误 : Converting circular structure to JSON: Is there any way to ignore this warning?

android - 使用 volley 以 json 格式将数据发布到服务器

javascript - 使用 JavaScript 检测硬重载

javascript - 通过 CARTO 从带有零 the_geom 参数的表创建 map

Cplex 中的 Python 稀疏矩阵?

json - 如何在 AJAX 中处理 AJAX 请求返回的空白 JSON 数据