gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:02:09 25 4
gpt4 key购买 nike

我想通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com