首页 > 解决方案 > 将 UDP 数据从 Python 发送到 Javascript?

问题描述

如何在 Javacript 中从此 Python 服务器检索数据。最终目标是能够使用 Python 变量来控制 Javascript 变量。我到处寻找有关如何使用套接字和 javascript 的提示,但他们只潜入发送数据,而我想接收数据。

提前致谢!:)

Python 服务器代码:

import socket
UDP_IP = socket.gethostname()
UDP_PORT = 5005
ip_address = socket.gethostbyname(socket.gethostname())

MESSAGE = "Hello, World!"

print ("UDP target IP:", UDP_IP)
print("IP Address is",ip_address)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)

sock = socket.socket(socket.AF_INET,  # Internet
                 socket.SOCK_DGRAM)  # UDP

#sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

sock.sendto(bytes(MESSAGE, "utf-8"), (ip_address, UDP_PORT))

JAVASCRIPT客户端:

var socket = io.connect('http://127.0.0.1:5005');

标签: javascriptpythonsocketsserverclient

解决方案


最好的选择应该是烧瓶

@app.route('/')
def hello():
   data = {'username': 'Pang', 'site': 'stackoverflow.com'}
   return render_template('settings.html', data=data)

在上面的代码中,您指定了路由和要发送的数据,之前在 python 变量中处理过。

在你的 js 中:

function myFunc(vars) {
return vars

}

通过这种方式,您应该能够查看您的值并使用它们

在你的 html

<html>
<head>
     <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
     <script type="text/javascript">
        myVar = myFunc({{vars|tojsenter code hereon}})
     </script>
</head>

在上面的代码中,您将接收到的数据存储在MyVar中,您可以省略 json 解析。


推荐阅读