00001 // Copyright 2003-2005 Arthur van Hoff, Rick Blair 00002 // Licensed under Apache License version 2.0 00003 // Original license LGPL 00004 00005 package javax.jmdns.impl; 00006 00007 import java.io.IOException; 00008 import java.net.DatagramPacket; 00009 import java.util.logging.Level; 00010 import java.util.logging.Logger; 00011 00012 import javax.jmdns.impl.constants.DNSConstants; 00013 00017 class SocketListener extends Thread { 00018 static Logger logger = Logger.getLogger(SocketListener.class.getName()); 00019 00023 private final JmDNSImpl _jmDNSImpl; 00024 00028 SocketListener(JmDNSImpl jmDNSImpl) { 00029 super("SocketListener(" + (jmDNSImpl != null ? jmDNSImpl.getName() : "") + ")"); 00030 this.setDaemon(true); 00031 this._jmDNSImpl = jmDNSImpl; 00032 } 00033 00034 @Override 00035 public void run() { 00036 try { 00037 byte buf[] = new byte[DNSConstants.MAX_MSG_ABSOLUTE]; 00038 DatagramPacket packet = new DatagramPacket(buf, buf.length); 00039 while (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled()) { 00040 packet.setLength(buf.length); 00041 this._jmDNSImpl.getSocket().receive(packet); 00042 if (this._jmDNSImpl.isCanceling() || this._jmDNSImpl.isCanceled() || this._jmDNSImpl.isClosing() || this._jmDNSImpl.isClosed()) { 00043 break; 00044 } 00045 try { 00046 if (this._jmDNSImpl.getLocalHost().shouldIgnorePacket(packet)) { 00047 continue; 00048 } 00049 00050 DNSIncoming msg = new DNSIncoming(packet); 00051 if (logger.isLoggable(Level.FINEST)) { 00052 logger.finest(this.getName() + ".run() JmDNS in:" + msg.print(true)); 00053 } 00054 if (msg.isQuery()) { 00055 if (packet.getPort() != DNSConstants.MDNS_PORT) { 00056 this._jmDNSImpl.handleQuery(msg, packet.getAddress(), packet.getPort()); 00057 } 00058 this._jmDNSImpl.handleQuery(msg, this._jmDNSImpl.getGroup(), DNSConstants.MDNS_PORT); 00059 } else { 00060 this._jmDNSImpl.handleResponse(msg); 00061 } 00062 } catch (IOException e) { 00063 logger.log(Level.WARNING, this.getName() + ".run() exception ", e); 00064 } 00065 } 00066 } catch (IOException e) { 00067 if (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled() && !this._jmDNSImpl.isClosing() && !this._jmDNSImpl.isClosed()) { 00068 logger.log(Level.WARNING, this.getName() + ".run() exception ", e); 00069 this._jmDNSImpl.recover(); 00070 } 00071 } 00072 if (logger.isLoggable(Level.FINEST)) { 00073 logger.finest(this.getName() + ".run() exiting."); 00074 } 00075 } 00076 00077 public JmDNSImpl getDns() { 00078 return _jmDNSImpl; 00079 } 00080 00081 }