将UDP数据从Pyhton发送到Javascript?
如何在Javascript中从这个Python服务器检索数据。最终目标是能够使用Python变量控制Javascript变量。我到处寻找关于如何使用套接字和javascript的提示,但他们只关注发送数据,而我希望接收数据 提前感谢!:) Python服务器代码:将UDP数据从Pyhton发送到Javascript?,javascript,python,sockets,server,client,Javascript,Python,Sockets,Server,Client,如何在Javascript中从这个Python服务器检索数据。最终目标是能够使用Python变量控制Javascript变量。我到处寻找关于如何使用套接字和javascript的提示,但他们只关注发送数据,而我希望接收数据 提前感谢!:) Python服务器代码: import socket UDP_IP = socket.gethostname() UDP_PORT = 5005 ip_address = socket.gethostbyname(socket.gethostname())
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=myFunc({{vars | tojsenter code hereon}})
在上面的代码中,您将接收到的数据存储在MyVar中,您可以省略json解析。而不是执行ip_address=socket.gethostbyname(socket.gethostname()),请编写ip_address=socket.gethostbyname(“”),这是更好的做法。如果您打算控制要在js中使用的python变量,那么更好的选择是python的FlaskRESTAPI。