栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您需要的是一端的套接字服务器

python
和javascript端的客户端/请求服务器。

对于python服务器端,请参考

SocketServer
,(也取自该示例),您需要确保的一件事是让套接字过去
NAT
(可能是端口转发)。另一种选择是
Twisted
一个非常强大的框架,我相信它具有通过发送数据的功能
NAT

import SocketServerclass 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
    ,https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-22/web-sockets的第22章

  • 最后看看

    jssockets

例:

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

希望有帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号