protected void Listen() {
if (Thread.CurrentThread.Name == null) {
Thread.CurrentThread.Name = "iphandler_thread";
}
ArrayList sockets = new ArrayList();
sockets.Add(_uc);
if(_mc != null) {
sockets.Add(_mc);
}
byte[] buffer = new byte[Int16.MaxValue];
DateTime last_debug = DateTime.UtcNow;
TimeSpan debug_period = TimeSpan.FromSeconds(5);
while(1 == _running) {
if (ProtocolLog.Monitor.Enabled) {
DateTime now = DateTime.UtcNow;
if (now - last_debug > debug_period) {
last_debug = now;
ProtocolLog.Write(ProtocolLog.Monitor, String.Format("I am alive: {0}", now));
}
}
try {
ArrayList readers = (ArrayList) sockets.Clone();
Socket.Select(readers, null, null, 10000000); //10 seconds
foreach(Socket socket in readers) {
EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
int rec_bytes = socket.ReceiveFrom(buffer, ref ep);
Subscriber s = _sub;
//s can't change once we've read it.
if( s != null && rec_bytes > 0) {
MemBlock packet = MemBlock.Copy(buffer, 0, rec_bytes);
MemBlock cookie = packet.Slice(0, 4);
if(cookie.Equals(MagicCookie)) {
packet = packet.Slice(4);
ISender sender = CreateUnicastSender(ep);
s.Handle(packet, sender);
}
}
}
}
catch(ObjectDisposedException odx) {
//If we are no longer running, this is to be expected.
if(1 == _running) {
//If we are running print it out
ProtocolLog.WriteIf(ProtocolLog.Exceptions, odx.ToString());
}
break;
}
catch(Exception x) {
if(0 == _running) {
ProtocolLog.WriteIf(ProtocolLog.Exceptions, x.ToString());
}
}
}
}