Skip to content

Instantly share code, notes, and snippets.

@arthurafarias
Created December 2, 2016 00:34
Show Gist options
  • Save arthurafarias/7258a2b83433dfda013f1954aaecd50a to your computer and use it in GitHub Desktop.
Save arthurafarias/7258a2b83433dfda013f1954aaecd50a to your computer and use it in GitHub Desktop.
UDP Simple Client and Threaded Server written in Python
import socket
import sys
HOST, PORT = "localhost", 8888
data = " ".join(sys.argv[1:])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)
print("Sent: {}".format(data))
print("Received: {}".format(received))
import SocketServer, threading, time
class ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
current_thread = threading.current_thread()
print("{}: client: {}, wrote: {}".format(current_thread.name, self.client_address, data))
socket.sendto(data.upper(), self.client_address)
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 8888
server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
try:
server_thread.start()
print("Server started at {} port {}".format(HOST, PORT))
while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
server.shutdown()
server.server_close()
exit()
@emilakesson99
Copy link

This is ass

@arthurafarias
Copy link
Author

arthurafarias commented Nov 3, 2022

uff...

In this time I was using gist as pastebin.

Gonna elaborate an example over an udp server and put here.

😅

@ykonoclast
Copy link

Well, I remember I did find it helpful at the time. I was getting started on Python.

@arthurafarias
Copy link
Author

I don't understand why this guy say "this is ass". This is the first result on google when someone asks for python threaded udp server, maybe it's helpful to people.

Anyway...

You can find a better description on how to make a threaded UDP Server to handle a lot of requests at same time using python here:

https://docs.python.org/3/library/socketserver.html

@arthurafarias
Copy link
Author

Well, I remember I did find it helpful at the time. I was getting started on Python.

Thank you!! =D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment