简体   繁体   中英

Send UDP Data from Pyhton to Javascript?

How do I retrieve data fro this Python Server in Javacript. The end goal is to be able to use Python variables to Control Javascript variables. 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.

Thanks in Advance: :)

Python Server Code:

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:

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

Best option should be 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.

In your js:

function myFunc(vars) {
return vars

}

In this way you should be able to view your values and use them

In your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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