ShellRox
ShellRox

Reputation: 2602

Socket: Reading UDP Packet

I've been searching about this question, but i couldn't understand the question since it was not really general, I wouldn't find the solution to read UDP packets that contain UTF-8 text for example.

So i make a socket, that makes a UDP packet that contains UTF-8 text, and i send it like this:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 80
MESSAGE = "Hello, World!"

sock = socket.socket(socket.AF_INET, 
             socket.SOCK_DGRAM) 
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

Lets define this as sender.py.

Now i want to make a reciever.py script that will be executed after sender.py.

How can i make that? I've heard of Data, addr = udp.recvfrom(1024) but i'm not entirely sure how it works/how to use it.

So whenever i execute them together, Reciever.py can print UTF-8 text of UDP packet sent.

Upvotes: 3

Views: 10706

Answers (1)

jonathanking
jonathanking

Reputation: 652

You'll want the receiver to do several things:

  1. Create a socket sock using socket.socket.
  2. Bind to the socket using sock.bind.
  3. In an infinite loop, execute: data, addr = sock.recvfrom(1024).
  4. Now the received data is available for your use and you can handle it as you wish.

Note that the receiver will sleep, waiting until a message appears in the socket it has bound to. After handling the data, the loop will execute once again and the receiver will go back to sleep.

1024 corresponds to the maximum size message you can receive (around 1024 characters, since 1 character = 1 byte. If you want to be able to receive larger messages, make this value larger.

See https://wiki.python.org/moin/UdpCommunication for a detailed code example.

Upvotes: 3

Related Questions