1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.openejb.server.discovery; 18 19 import java.net.URI; 20 import java.net.MulticastSocket; 21 import java.net.InetAddress; 22 import java.net.DatagramPacket; 23 import java.util.concurrent.TimeUnit; 24 import java.io.IOException; 25 26 /** 27 * @version $Rev$ $Date$ 28 */ 29 public class MulticastSearch { 30 31 private static final int BUFF_SIZE = 8192; 32 33 private final MulticastSocket multicast; 34 35 public MulticastSearch() throws IOException { 36 this("239.255.3.2", 6142); 37 } 38 39 public MulticastSearch(String host, int port) throws IOException { 40 InetAddress inetAddress = InetAddress.getByName(host); 41 42 multicast = new MulticastSocket(port); 43 multicast.joinGroup(inetAddress); 44 multicast.setSoTimeout(500); 45 } 46 47 public URI search(int timeout, TimeUnit milliseconds) throws IOException { 48 return search(new DefaultFilter(), timeout, milliseconds); 49 } 50 51 public URI search() throws IOException { 52 return search(new DefaultFilter(), 0, TimeUnit.MILLISECONDS); 53 } 54 55 public URI search(Filter filter) throws IOException { 56 return search(filter, 0, TimeUnit.MILLISECONDS); 57 } 58 59 public URI search(Filter filter, long timeout, TimeUnit unit) throws IOException { 60 timeout = unit.convert(timeout, TimeUnit.MILLISECONDS); 61 long waited = 0; 62 63 byte[] buf = new byte[BUFF_SIZE]; 64 DatagramPacket packet = new DatagramPacket(buf, 0, buf.length); 65 66 while (timeout == 0 || waited < timeout){ 67 long start = System.currentTimeMillis(); 68 try { 69 multicast.receive(packet); 70 if (packet.getLength() > 0) { 71 String str = new String(packet.getData(), packet.getOffset(), packet.getLength()); 72 URI service = URI.create(str); 73 if (service != null && filter.accept(service)) { 74 return service; 75 } 76 } 77 } finally { 78 long stop = System.currentTimeMillis(); 79 waited += stop - start; 80 } 81 } 82 83 return null; 84 } 85 86 public interface Filter { 87 boolean accept(URI service); 88 } 89 90 public static class DefaultFilter implements Filter { 91 public boolean accept(URI service) { 92 return true; 93 } 94 } 95 }