⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 upnpdiscovery.java

📁 国外的j2me播放器软件
💻 JAVA
字号:
package no.auc.one.portableplayer.communication;

import java.io.IOException;
import java.util.*;
import javax.microedition.io.*;

import org.apache.log4j.*;

/**
 * For discovering UPnP devices and services, using Simple Search and 
 * Discovery Protocol (SSDP).
 *
 * @version $Revision: 1.6.2.3 $
 *
 * $Id: UPnPDiscovery.java,v 1.6.2.3 2006/07/11 13:34:07 ahaeber Exp $
 */
public class UPnPDiscovery {
    private static Logger LOG = Logger.getLogger("Disco");
    
    private DiscoveryWorker dwWorker = null;
    private WorkKiller discoKiller = null;
    
    /**
     * Does a synchronous UPnP discovery request. The request is sent using 
     * HTTPMU (UDP multicast), following SSDP.
     * 
     * @param searchRequest What to search for. This will be used for the ST 
     *        header of the request.
     *
     * @param maxDuration Maximum time for the request to last. When the time 
     *        is up a watchdog thread will interrupt it.
     *
     * @return Location URLs (of type String) discovered.
     */
    public Vector start(
        String searchRequest, 
        long maxDuration)
	{
        LOG.debug("Start UPnP Discovery Request");

		Vector replies = new Vector();
        Timer t = new Timer();
        
		dwWorker = new DiscoveryWorker(
			searchRequest,
            maxDuration,
			replies);
        discoKiller = new WorkKiller();
        
        dwWorker.start();
        
		//
        // Schedule DiscoveryWorker to be canceled after maxDuration seconds
        //
        t.schedule(discoKiller, (maxDuration * 1000) + 1000); 
    
        synchronized(dwWorker) {
            try{
                LOG.debug("Waiting for dwWorker to be killed by watchdog");
                dwWorker.wait();
                LOG.debug("Finished waiting for dwWorker");
		    } catch (InterruptedException ioe) {
                LOG.debug("InterruptedException - waiting for worker");
                LOG.debug(ioe);
			    // DO NOTHING
		    }/* catch (Exception e) {
                LOG.debug("Exception occurred - waiting for worker");
                LOG.debug(e.toString());
            }*/
        }

		if (replies == null || replies.size() == 0) {
			LOG.debug("No replies found...");
			return null;
		} else {
			LOG.debug("Number of replies: " + replies.size());
		}
       		    
	    Vector locationUrls = replies;
	    
	    for(int i = 0; i < replies.size(); i++) {
            Object o = replies.elementAt(i);
            
            if (o == null || !(o instanceof String)) {
                replies.removeElementAt(i--);
                continue;
            }
            
	        String rep = (String)o;
	        String repLowerCase = rep.toLowerCase();
	        String loc=null;
		    int locStart = repLowerCase.indexOf("location:") + 9;
	        int locEnd = repLowerCase.substring(locStart).indexOf('\r');
	        loc=rep.substring(locStart, locStart + locEnd).trim();

	        if(locationUrls.contains(loc)) {
	            locationUrls.removeElementAt(i--);
            } else {
                locationUrls.setElementAt(loc, i);
            }
	    }
        
	    return locationUrls;
	}
	
    public void cancel() throws IOException {        
        try {
            cancelDisco();
        } finally {
            discoKiller.cancel();
        }
    }

    private void cancelDisco() throws IOException {
        LOG.debug("Cancel discovery");
        
        if(dwWorker.conn != null) {
            dwWorker.conn.close();
            dwWorker.conn = null;
        } else {
            LOG.debug("Worker's connection is null");
        }
    }
    
    private class WorkKiller extends TimerTask {
        public void run() {
            LOG.debug("WorkKiller RUN");
            LOG.debug(
                "Starting time diff: " + 
                (System.currentTimeMillis() - scheduledExecutionTime()));
            
            try {
                cancelDisco();
                dwWorker.notify();
            } catch (IOException ioe) {
                LOG.fatal("IOException killing worker");
                LOG.fatal(ioe);
            }
        }
    }

    /**
     * Helper class for discovering UPnP entities.
     */
	private class DiscoveryWorker extends Thread {
	   	public UDPDatagramConnection conn = null;
		Vector replies;
		String searchRequest;
        long maxDuration;
			
		public DiscoveryWorker(
            String ssdpSearchString, 
            long maxDuration, 
            Vector replies) 
        {
			this.replies = replies;
            this.maxDuration = maxDuration;
			searchRequest = ssdpSearchString;
		}
			
		public void run() {		
	    	try{
				String url = "datagram://239.255.255.250:1900";
				Datagram dgRecv = null;
		        Datagram dgSend = null;			  			
		        StringBuffer msg = new StringBuffer();
	
		        msg.append("M-SEARCH * HTTP/1.1\r\n");
		        msg.append("HOST: 239.255.255.250:1900\r\n");
		        msg.append("MAN: \"ssdp:discover\"\r\n");
		        msg.append("MX: " + maxDuration + "\r\n");
		        msg.append("ST: " + searchRequest + "\r\n\r\n");
		        
		        byte[] msgBytes = msg.toString().getBytes();
	
		        conn = (UDPDatagramConnection)Connector.open(url);
		        dgSend = conn.newDatagram(msgBytes, msgBytes.length);
				conn.send(dgSend);
	
		        dgRecv = conn.newDatagram(1024);
                
		        while(true) {
	            	conn.receive(dgRecv);
	           
	            	replies.addElement(
                        new String(
                            dgRecv.getData(), 
                            dgRecv.getOffset(), 
                            dgRecv.getLength()));
                    dgRecv.reset();
                    dgRecv.setLength(1024);
		        }			    
		    } catch(IOException e) {
                LOG.debug("DiscoWork/IOException");
                LOG.debug(e);
            } finally {
                // cancelDisco, which is invoked by WorkKiller or by the UI, 
                // will set conn to null. If not then the conn could be open, 
                // but exception happened for some other reason.
                if (conn != null) {
                    try {
                        conn.close();
                        conn = null;
                    } catch (Exception e) {
                        // Do nothing, just swallow it
                    }   
                }
            }
		}	
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -