问题描述
我想通过 python 提供来自 javascript 代码的查询.但我在这个领域完全没有经验.我想构建的是这样的:
1.request.js:
open_connection('server.py');for (var i=0; i
2.server.py
x = 0连接时:如果要求:发送(x)x = x + 1
我听说过 JSON,但不知道我是否应该使用它.(?)
能否请您给我一些代码示例或指导如何实现上述两个文件?
解决方案
您需要的是
python
端的套接字服务器和 javascript 端的客户端/请求服务器.
python服务器端参考
SocketServer
,(示例也取自那里),您必须确保的一件事是让套接字通过 NAT
(可能是端口转发).另一种选择是 Twisted
这是一个非常强大的框架,我相信它有功能通过NAT
发送数据.
导入SocketServer类 MyTCPHandler(SocketServer.BaseRequestHandler):"""我们服务器的 RequestHandler 类.每次连接到服务器时,它都会被实例化一次,并且必须覆盖 handle() 方法以实现与客户."""定义句柄(自我):# self.request 是连接到客户端的 TCP 套接字self.data = self.request.recv(1024).strip()打印 "{} 写道:".format(self.client_address[0])打印 self.data# 只发回相同的数据,但大写self.request.sendall(self.data.upper())如果 __name__ == "__main__":主机, 端口 = "本地主机", 9999# 创建服务器,绑定到 localhost 9999 端口server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)# 激活服务器;这将继续运行,直到你# 使用 Ctrl-C 中断程序server.serve_forever()
在
JavaScript
上有很多允许socket连接的框架,这里有几个
示例:
<脚本>var socket = io.connect('http://localhost');socket.on('news', function (data) {控制台日志(数据);socket.emit('我的另一个事件', { my: 'data' });});
您甚至可以使用
HTML5 Web Sockets
示例:
var connection = new WebSocket('ws://IPAddress:Port');connection.onopen = 函数 () {connection.send('Ping');//向服务器发送消息Ping"};
另外,看看本书的一部分,
Javascript: The Definitive Guide
的第 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();
希望对您有所帮助!
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:
open_connection('server.py');
for (var i=0; i<10; i++)
document.write(request_next_number());
close_connection('server.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. (?)
Could you please give me some code examples or guides how to implement the two files above?
解决方案
What you need is a socket server on the
python
end and a client/request server on the javascript end.
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 Twisted
which is a very powerful framework, i believe it has functionality to send data through 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
JavaScript
there are many frameworks that allow socket connections, here are a few
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>
You can even use
HTML5 Web Sockets
Example:
var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
Also, take a look at a part of this book , Chapter 22 of
Javascript: The Definitive Guide
, https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-22/web-socketsFinally, take a look at
jssockets
Example:
_jssocket.setCallBack(event, callback);
_jssocket.connect(ip,port);
_jssocket.write(message);
_jssocket.disconnect();
Hope this help!
这篇关于将python连接到javascript进行双向通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!