■ ■ ■ ■ ■ ■
Projects/0_UDP_server/UDPserver.py
| 1 | + | |
| 2 | + | import socket |
| 3 | + | |
| 4 | + | localIP = "127.0.0.1" |
| 5 | + | localPort = 20001 |
| 6 | + | bufferSize = 1024 |
| 7 | + | msgFromServer = "Message received on UDP Client and sending it again: " |
| 8 | + | |
| 9 | + | # Create a datagram socket |
| 10 | + | UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) |
| 11 | + | |
| 12 | + | # Bind to address and ip |
| 13 | + | UDPServerSocket.bind((localIP, localPort)) |
| 14 | + | |
| 15 | + | print("UDP server up and listening") |
| 16 | + | |
| 17 | + | # Listen for incoming datagrams |
| 18 | + | while(True): |
| 19 | + | message, address = UDPServerSocket.recvfrom(bufferSize) |
| 20 | + | |
| 21 | + | print("\nMessage from Client:{0} \nClient IP Address:{1} \n".format(message.decode('UTF-8'),address)) |
| 22 | + | |
| 23 | + | bytesTosend = msgFromServer + message.decode('UTF-8') |
| 24 | + | # Sending a reply to client |
| 25 | + | UDPServerSocket.sendto(str.encode(bytesTosend), address) |