I'm quite sure I'm the problem here, but I can't separate myself to understand what I've done wrong.
I'm using epoll
to check if there's data in the pipe from clients.
If there is, retrieve it and just put it in a placeholder and if the data is len(0)
or less, disconnect.
But for whatever reason, .recv(8192)
becomes a blocking call holding up the code for 5 solid seconds. Which is coincidentally the same amount I'm using as as sleep on my thread in the client application for the first thread.
Server side:
import sys
from select import epoll, EPOLLIN, EPOLLHUP
from socket import *
from time import time
socks = {}
polly = epoll()
sock = socket()
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(('', 1337))
sock.listen(4)
mainFid = sock.fileno()
polly.register(mainFid, EPOLLIN)
while 1:
for fid, eid in polly.poll(0.25):
#print('New event:', fid, eid)
if fid == mainFid:
ns, na = sock.accept()
polly.register(ns.fileno())
print(time(), na,'connected', ns.fileno())
socks[ns.fileno()] = {'sock' : ns, 'addr' : na}
elif fid in socks:
print(time(), 'Client is sending data!')
data = socks[fid]['sock'].recv(8192)
print(time(), 'Data recieved successfully.')
if len(data) <= 0: socks[fid]['sock'].close()
Client side:
from socket import *
from time import sleep, time
from threading import *
class aClient(Thread):
def __init__(self, delay=5):
Thread.__init__(self)
self.s = socket()
self.delay = delay
print(time(), 'Connecting.')
self.s.connect(('127.0.0.1', 1337))
self.start()
def run(self):
print(time(), 'Sending data.')
self.s.send(b'Get me data!')
print(time(), 'Data has been sent.')
sleep(self.delay)
self.s.close()
aClient()
sleep(2)
aClient(10)
I can't for the love of it all understand why recv()
becomes a blocking call, there's obviously(?) data in the pipe..
For starters, this makes the code useless in terms of speed, but also clients will received "Connection refused" because I'm not picking them up quickly enough because I send way to much time in recv()
.
Using python -m trace --trace test_socket.py
it also shows that it gets stuck on:
test_socket.py(27): data = socks[fid]['sock'].recv(8192)
Whenever the client disconnects the recv()
releases, that's the correlation between the clients sleep.
And this is normally not how it's supposed to happen.
I've tested on two different machines including not using 127.0.0.1
as the source and destination. Same thing there. And searching for a solution just returns my own solutions on SO threads