javascript - 将 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');
解决方案
最好的选择应该是烧瓶
@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 解析。
推荐阅读
- python - Python:如何在创建 f 字符串后对其进行评估
- electron - Electron.js 如何实现在屏幕边框上半隐藏的浮动桌面图标按钮
- r - H2O 隔离林中是否有衡量模型在没有标签的数据集上的性能的指标?
- python - 在 databricks 集群中使用初始化脚本安装 python 包
- pyspark - 如何将密集向量转换为pyspark中的数据框?
- html - 如何更改每个 @media 屏幕的 CSS 类?
- mysql - MySQL 使用 SUM 连接表
- python - 如何让我的按钮与 tkinter 中的中心对齐?
- bluetooth-lowenergy - BLE Smart 4.2 自动化 - 如果可能的话,如何绕过安全层 [用于测试自动化]
- r - 下载时自定义文件名