Skip to content

Instantly share code, notes, and snippets.

@Alrighttt
Created June 18, 2020 12:00
Show Gist options
  • Save Alrighttt/fd52f202f38dbc95ccfc71427382683f to your computer and use it in GitHub Desktop.
Save Alrighttt/fd52f202f38dbc95ccfc71427382683f to your computer and use it in GitHub Desktop.
thrown together for zeno issue #5
#!/usr/bin/env python3
import binascii
import sys
import logging
import time
import gevent
from gevent import socket
def receive(sock,addr):
logging.info("New receive thread: %s", str(addr))
while True:
gevent.sleep(0.001)
data, alive = sock.recvfrom(1024)
if data == b'': # FIXME when connection is dropped, recvfrom no longer locks? dangerous loop
logging.info('Dropped incoming connection from: %s', str(addr))
sock.close()
break
logging.info("RECEIVED:%s: %s", str(sock.getpeername()),data.hex())
logging.info("ASCII: %s", binascii.unhexlify(data.hex()))
logging.info('Dropped incoming connection from: %s', str(addr))
sock.close()
break
def listen(sock):
logging.info("New listen thread")
while True:
gevent.sleep(0.001)
clientSocket, addr = sock.accept()
logging.info("New incoming connection: %s", str(addr))
gevent.spawn(receive, clientSocket, addr)
def init_listen(port, MAX_CONNECTIONS):
pysock = gevent.socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
attempts = 0
while True:
attempts += 1
logging.info('Attempting to bind to %s', str(('', port)))
if attempts > 10:
sys.exit('Could not bind to ' + str(('', port)) + ' exiting...' )
try:
pysock.bind(('', port))
logging.info('Listening on %s', str(('', port)))
break
except OSError as e:
if e.errno == 98:
logging.info('Unable to bind to ' + str(('', port)))
time.sleep(1)
pysock.listen(MAX_CONNECTIONS)
return(pysock)
logging.basicConfig(format='%(asctime)s: %(message)s', level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
# init settings, will make these based on config file or command line args
PY_PORT = 8888
if __name__ == '__main__':
for i in range(0,1000):
what = []
for i in range(PY_PORT, PY_PORT+100):
pysock = init_listen(i, 2)
what.append(gevent.spawn(listen, pysock))
gevent.joinall(what)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment