将python连接到javascript以进行双向通信 [英] connecting python to javascript for two-direction communication

查看:267
本文介绍了将python连接到javascript以进行双向通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要通过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 
b $ b如果请求:
send(x)
x = x + 1

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



请给我一些代码示例或指导如何实现上述两个文件?

解决方案

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



有关python服务器端,请参阅 SocketServer (例子也是从那里获取),你必须确保套接字过去 NAT (可能端口转发)。另一个选择是 Twisted ,这是一个非常强大的框架,我相信它有通过 NAT 发送数据的功能。

  import SocketServer 

class MyTCPHandler(SocketServer.BaseRequestHandler):

我们的服务器的RequestHandler类

每次连接到服务器时被实例化一次,必须
重写handle()方法来实现与
客户端的通信。


def handle(self):
#self.request是连接到客户端的TCP套接字
self.data = self.request。 recv(1024).strip()
print{} written:。format(self.client_address [0])
print self.data
#发回相同的数据,上层的
self.request.sendall(self.data.upper())

如果__name__ ==__main__:
HOST,PORT =localhost,9999

#创建服务器,绑定到本地端口9999
server = SocketServer.TCPServer((HOST,PORT),MyTCPHandler)

#激活服务器;这将继续运行,直到
#中断程序与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'); //向服务器发送消息Ping
      };





      p>

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

      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
      

      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>
      

      Example:

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

      Example:

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

      Hope this help!

      这篇关于将python连接到javascript以进行双向通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆