Skip to content

Instantly share code, notes, and snippets.

@jac18281828
Last active June 21, 2016 15:29
Show Gist options
  • Save jac18281828/44bfd894d5c8af4533193f5d84e26e32 to your computer and use it in GitHub Desktop.
Save jac18281828/44bfd894d5c8af4533193f5d84e26e32 to your computer and use it in GitHub Desktop.
import socket
import select
import sys
__EPOLL_TIMEOUT = 1.0
__BUFFER_SZ = 8192
yeti_request ="GET /bap HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n"
epoll = None
socket_set = {}
def sendAll():
"""Send yeti_request on socket"""
for id in socket_set.keys():
s = socket_set[id]
n = s.send(yeti_request)
print "Sent: {}".format(yeti_request[0:n])
if(n < len(yeti_request)):
raise Error("Socket buffer full")
def send(id):
"""Send yeti_request on socket"""
if id in socket_set.keys():
s = socket_set[id]
n = s.send(yeti_request)
print "Sent: {}".format(yeti_request[0:n])
if(n < len(yeti_request)):
raise Error("Socket buffer full")
return n
def mux_epoll():
"""Run the epoll select loop one time through"""
events = epoll.poll(__EPOLL_TIMEOUT)
for fileno, event in events:
if event & select.EPOLLIN:
try:
s = socket_set[fileno]
resp=s.recv(__BUFFER_SZ)
if(len(resp) > 0):
if "404" in resp or "204" in resp or "200" in resp:
sys.stdout.write("Recv[{}]: {}".format(fileno, resp))
#send(s.fileno())
else:
sys.stadout.write(resp)
else:
s.close()
del socket_set[fileno]
except socket.error as msg:
logging.error("Failed to read. {}".format(msg));
s = socket_set[fileno]
s.close()
del socket_set[fileno]
elif event & select.EPOLLHUP:
s = socket_set[fileno]
s.close()
del socket_set[fileno]
def mux_select():
"""Run the epoll select loop one time through"""
events = select.select(socket_set.keys(), [], [], __EPOLL_TIMEOUT)
for sid in events[0]:
s = socket_set[sid]
fileno = s.fileno()
try:
resp=s.recv(__BUFFER_SZ)
if(len(resp) > 0):
if("404" in resp) or "204" in resp or "200" in resp:
sys.stdout.write("Recv[{}]: {}".format(fileno,resp))
#send(sid)
else:
sys.stdout.write(resp)
else:
s.close()
del socket_set[fileno]
except socket.error as msg:
logging.error("Failed to read. {}".format(msg));
s.close()
del socket_set[fileno]
# Ack! Dirty MacOS!
#epoll = select.epoll()
for i in range(4):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 8088))
s.setblocking(0)
socket_set[s.fileno()] = s
#epoll.register(s.fileno(), select.EPOLLIN)
sendAll()
while len(socket_set) > 0:
mux_select()
@jac18281828
Copy link
Author

python select and epoll example - epoll does not work on MacOS

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