Skip to content

Instantly share code, notes, and snippets.

@Zxilly
Last active May 14, 2024 04:51
Show Gist options
  • Save Zxilly/eaf52c9facb06b51f3192f2f1903f350 to your computer and use it in GitHub Desktop.
Save Zxilly/eaf52c9facb06b51f3192f2f1903f350 to your computer and use it in GitHub Desktop.
import socket
import argparse
import threading
import logging
def main(server_ip, server_port, log_file):
logging.basicConfig(filename=log_file, level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:
server_socket.bind((server_ip, server_port))
logging.info(f"Server is listening on {server_ip}:{server_port}")
while True:
data, client_address = server_socket.recvfrom(10000)
logging.info(f"Received data from {client_address}: {len(data)}")
server_socket.sendto(data, client_address)
logging.info(f"Sent data back to {client_address}: {len(data)}")
def run_server_in_background(server_ip, server_port, log_file):
server_thread = threading.Thread(target=main, args=(server_ip, server_port, log_file), daemon=True)
server_thread.start()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="UDP server with command line arguments")
parser.add_argument("--server_ip", default="0.0.0.0", help="Server IP address")
parser.add_argument("--port", default=45793, type=int, help="Server port number")
parser.add_argument("--background", action="store_true", help="Run server in background")
parser.add_argument("--log_file", default="server.log", help="Log file path")
args = parser.parse_args()
if args.background:
run_server_in_background(args.server_ip, args.port, args.log_file)
else:
main(args.server_ip, args.port, args.log_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment