加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

将python连接到javascript以进行双向通信

发布时间:2020-12-20 11:29:00 所属栏目:Python 来源:网络整理
导读:我想通过 python的 javascript代码提供查询.但我根本没有这方面的经验.我想建立的是这样的: 1. request.js : open_connection('server.py');for (var i=0; i10; i++) document.write(request_next_number());close_connection('server.py') 2. server.py x
我想通过 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章,第07章
>最后,看看jssockets

例:

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

希望这有帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读