将python连接到javascript进行双向通信
connecting python to javascript for two-direction communication
我想通过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
上有许多允许套接字连接的框架,以下是一些
Socket IO
示例:
<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: 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();
希望得到帮助!
WebSocket的一个例子,我用它将图像传输到Web服务器并流式传输我的屏幕。
stream.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
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;
}
}
服务器.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()
您将需要高速公路(您可以使用pip install autobahn
安装它)
相关文章:
- 用于本地主机上进程间通信的Javascript中的UDP
- 带有 TCP/IP 通信的 JavaScript 十六进制代码
- 如何在Windows Phone 8.1应用程序中在C#和Javascript之间传递数据或通信
- 在Jquery或Javascript中获取两个范围或日期之间的通信周数
- 纯 Javascript 双向数据绑定
- jnlp与javascript的通信
- 使用HTML和Javascript进行双向通信
- 如何使用javascript在客户端通过串行端口进行通信
- IPython内核javascript双向通信的极简主义示例
- 指令和控制器之间的双向通信
- 将python连接到javascript进行双向通信
- 如何在服务之间进行双向通信
- 框架之间的双向通信
- AngularJS:通过服务在两个作用域/控制器之间进行双向通信
- 龙卷风双向通信没有websockets
- 如何在WebView之间进行通信JavaScript
- Meteor和Node之间的双向通信
- 使用python shell和node.js进行双向通信
- 与Node.js的双向通信
- 如何在RaspberryPi和远程托管的Webapp之间建立双向通信