简体   繁体   中英

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

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.

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)

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