我想通过 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>
- 您甚至可以使用
HTML5 Web Sockets
示例:
var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
另外,请看一下本书的一部分,
Javascript:权威指南
的第 22 章,https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-22/web-sockets最后看一下
jssockets
示例:
_jssocket.setCallBack(event, callback);
_jssocket.connect(ip,port);
_jssocket.write(message);
_jssocket.disconnect();
希望这有帮助!
关于javascript - 连接 python 和 javascript 进行双向通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233433/