Skip to content

Instantly share code, notes, and snippets.

@MisakaMikoto-35c5
Created September 22, 2019 13:34
Show Gist options
  • Save MisakaMikoto-35c5/fd75911330b5141f01ca5fe7d9d77e7d to your computer and use it in GitHub Desktop.
Save MisakaMikoto-35c5/fd75911330b5141f01ca5fe7d9d77e7d to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
# Source: https://python3-cookbook.readthedocs.io/zh_CN/latest/c11/p02_creating_tcp_server.html
import socket
import random
import threading
from socketserver import ThreadingTCPServer
from socketserver import StreamRequestHandler, TCPServer
class EchoHandler(StreamRequestHandler):
# Optional settings (defaults shown)
timeout = 20 # Timeout on all socket operations
rbufsize = -1 # Read buffer size
wbufsize = 0 # Write buffer size
disable_nagle_algorithm = False # Sets TCP_NODELAY socket option
def generate_random_bytes(self, length):
numbers_array = []
for unused in range(0, length):
numbers_array.append(random.randrange(0, 256))
payload = bytearray(numbers_array)
return payload
def handle(self):
print('Got connection from', self.client_address)
def threaded_receiver():
try:
while True:
msg = self.request.recv(2048).strip()
#print(msg)
if not msg:
break
except Exception:
return
try:
#threading.Thread(target=threaded_receiver).start()
self.request.sendall(self.generate_random_bytes(random.randint(256, 4096)))
self.request.close()
except socket.timeout:
print('Timed out!')
self.request.close()
if __name__ == '__main__':
serv = TCPServer(('', 80), EchoHandler)
serv.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment