Samuel Brand
Samuel Brand

Reputation: 11

UDP sockets with Python

I am trying to make a server capable of receiving and sending data using udp, I have reviewed some codes but they send or receive data, but not both, I am trying to send the data through one port and receive it by another, however I could not.

Had I thought about using the accept () function as in TCP, is there a similar way in UDP or a better solution? Thank you

while True:                                                 
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.sendto(MESSAGE, (UDP_IP, UDP_PORT1))
  data, addr = sock.recvfrom(1024)
  print data

Upvotes: 1

Views: 5370

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177674

If you're a UDP listener, you bind a port to the socket. If you are sender, you don't need to bind a port:

echo server

from socket import *

s = socket(type=SOCK_DGRAM)
s.bind(('localhost',5000))

while True:
    data,addr = s.recvfrom(1024)
    print(data,addr)
    s.sendto(data,addr)

client

from socket import *

s = socket(type=SOCK_DGRAM)
s.sendto(b'hello',('localhost',5000))
data,addr = s.recvfrom(1024)
print(data,addr)

Start the server then run the client.

Client output:

C:\>client.py
b'hello' ('127.0.0.1', 5000)

C:\>client.py
b'hello' ('127.0.0.1', 5000)

Server output:

C:\>server.py
b'hello' ('127.0.0.1', 50391)
b'hello' ('127.0.0.1', 50392)

Upvotes: 2

Jeremy Friesner
Jeremy Friesner

Reputation: 73081

accept() is a TCP-only function, it has no application in UDP networking, so don't bother with it unless you are trying to use TCP.

As for sending data from one port while receiving it from another, the simple way to do that is to create two UDP sockets. You can then call recvfrom() on one of them and sendto() on the other one.

Upvotes: 1

Related Questions