-
-
Notifications
You must be signed in to change notification settings - Fork 348
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
What about UDP ? #537
Comments
Good question! Trio doesn't currently have any "high level abstraction" for working with UDP, because UDP is pretty low-level :-). But you can use UDP with trio by using the "low level" module The For example, here's some regular python code from https://wiki.python.org/moin/UdpCommunication (I added parentheses to the import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print("UDP target IP:", UDP_IP)
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)) And here's the same code, but adapted for trio: import trio
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
async def main():
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = trio.socket.socket(trio.socket.AF_INET, # Internet
trio.socket.SOCK_DGRAM) # UDP
await sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
trio.run(main) So the differences are:
And here's the server code from that page adapted to trio as well. If you run this, and then run the first program in a different terminal, you should see that it successfully sends and receives a message. (Unless I messed something up... I'm typing this on my phone so I can't test them myself!) import trio
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
async def main():
sock = trio.socket.socket(trio.socket.AF_INET, # Internet
trio.socket.SOCK_DGRAM) # UDP
await sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = await sock.recvfrom(1024) # buffer size is 1024 bytes
print("received message:", data)
print("from:", addr)
trio.run(main) |
Here's a more detailed example of using UDP with Trio: https://github.com/python-trio/trio/blob/master/notes-to-self/ntp-example.py |
Thanks very much. |
Glad that helped! If you have more questions feel free to ask here or in chat. Or even if you don't have a question, we'd love to hear more about what you're working on :-) |
HI,can anybody give me some code deal with UDP stream ?
I searched the repository,but got nothing.
The text was updated successfully, but these errors were encountered: