Difference between revisions of "Python3: socketserver.UDPServer"
Jump to navigation
Jump to search
Onnowpurbo (talk | contribs) |
Onnowpurbo (talk | contribs) |
||
(2 intermediate revisions by the same user not shown) | |||
Line 22: | Line 22: | ||
with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: | with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: | ||
server.serve_forever() | server.serve_forever() | ||
− | |||
− | |||
− | |||
− | |||
Line 50: | Line 46: | ||
==Run== | ==Run== | ||
+ | |||
+ | python3 UDPServer.py | ||
+ | python3 UDPClient.py test | ||
==Pranala Menarik== | ==Pranala Menarik== | ||
* [[Python3]] | * [[Python3]] |
Latest revision as of 09:20, 24 November 2018
Server side
import socketserver class MyUDPHandler(socketserver.BaseRequestHandler): """ This class works similar to the TCP handler class, except that self.request consists of a pair of data and client socket, and since there is no connection the client address must be given explicitly when sending data back via sendto(). """ def handle(self): data = self.request[0].strip() socket = self.request[1] print("{} wrote:".format(self.client_address[0])) print(data) socket.sendto(data.upper(), self.client_address) if __name__ == "__main__": HOST, PORT = "localhost", 9999 with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server: server.serve_forever()
Client side
import socket import sys HOST, PORT = "localhost", 9999 data = " ".join(sys.argv[1:]) # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # As you can see, there is no connect() call; UDP has no connections. # Instead, data is directly sent to the recipient via sendto(). sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT)) received = str(sock.recv(1024), "utf-8") print("Sent: {}".format(data)) print("Received: {}".format(received))
Run
python3 UDPServer.py python3 UDPClient.py test