简体   繁体   English

将 UDP 数据从 Pyhton 发送到 Javascript?

[英]Send UDP Data from Pyhton to Javascript?

How do I retrieve data fro this Python Server in Javacript.如何在 Javacript 中从此 Python 服务器检索数据。 The end goal is to be able to use Python variables to Control Javascript variables.最终目标是能够使用 Python 变量来控制 Javascript 变量。 I've scoured everywhere for hints on how to work with sockets and javascript but they only dive into sending data whereas I'm wanting to receive data.我到处寻找有关如何使用 sockets 和 javascript 的提示,但他们只潜入发送数据,而我想接收数据。

Thanks in Advance: :)提前致谢: :)

Python Server Code: 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 CLIENT: JAVASCRIPT 客户:

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

Best option should be flask最佳选择应该是 flask

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

In the above code you specify the route and the data you want to send, previously processed in a python variable.在上面的代码中,您指定了要发送的路由和数据,之前在 python 变量中进行了处理。

In your js:在你的 js 中:

function myFunc(vars) {
return vars

} }

In this way you should be able to view your values and use them通过这种方式,您应该能够查看您的值并使用它们

In your html在您的 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>

In the above code you store your data reciebed in MyVar , you can omit the json parsing.在上面的代码中,您将收到的数据存储在MyVar中,您可以省略 json 解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM