var clientQueue : Deque<Socket> = new Deque();
private function run()
{
while(true)
{
var sock = serv.accept();
clientQueue.add(sock);
}
}
private var socks = []; // global socket list
private function readFromSockets():Void
{
var poll:Poll = new Poll(4096); // reserve 4096 positions for sockets upfront
var changed:Bool = false; // a variable that said - hey, your socket list is changed, you have to update it
var localSocks = []; // a local temp variable to hold values from socks
while (true)
{
while (true)
{
var s:Socket = clientQueue.pop(false);
if (s == null)
{
break;
}
socks.push(s);
changed = true;
}
if(changed)
{
changed = false;
localSocks = socks.concat([]); // we get a fresh copy, so in case socks will change for some reason in other thread or even in this one, we are on the safe side
poll.prepare(localSocks, []);
}
try poll.events(0.05)
catch (e:Dynamic){ changed = true;} // if there is an error, mostly sure some sockets are dead
var arr = [];
var i:Int = 0;
while (true)
{
var idx = poll.readIndexes[i]; // get indexes of sockets that are reading, each index is the position of the socket in localSocks array
if (idx < 0) // because the poll.readIndexes has a size of 4096, look at the constructor, all other values are -1
{
break;
}
arr.push(localSocks[idx]);
i++;
}
for ( s in arr)
{
try {
readData(socket);
} catch ( e : Dynamic ) {
s.close();
socks.remove(s);
}
}
}
}