Example #1
0
 public Object makeObject(Object key) throws Exception {
   ImmutableEndpoint ep = (ImmutableEndpoint) key;
   MulticastSocket socket = (MulticastSocket) super.makeObject(key);
   socket.setLoopbackMode(((MulticastConnector) ep.getConnector()).isLoopback());
   int ttl = ((MulticastConnector) ep.getConnector()).getTimeToLive();
   if (ttl != Connector.INT_VALUE_NOT_SET) {
     socket.setTimeToLive(ttl);
   }
   return socket;
 }
 @Override
 public void setLoopbackModeDisabled(boolean loopbackModeDisabled) {
   if (socket instanceof MulticastSocket) {
     try {
       ((MulticastSocket) socket).setLoopbackMode(loopbackModeDisabled);
     } catch (SocketException e) {
       throw new ChannelException(e);
     }
   } else {
     throw new UnsupportedOperationException();
   }
 }
Example #3
0
 public String findServerIpAddress() throws IOException {
   String deviceName = null;
   MulticastSocket multicastSocket = new MulticastSocket(MULTICAST_PORT);
   multicastSocket.setLoopbackMode(true);
   InetAddress group = InetAddress.getByName(GROUP_IP);
   multicastSocket.joinGroup(group);
   multicastSocket.setSoTimeout(5000);
   DatagramPacket packet;
   while (isRunning) {
     List<Device> lists = new ArrayList<Device>();
     try {
       byte[] receiveData = new byte[64];
       packet = new DatagramPacket(receiveData, receiveData.length);
       multicastSocket.receive(packet);
       String deviceIp = packet.getAddress().toString();
       deviceIp = deviceIp.substring(1, deviceIp.length()); // ip地址
       StringBuilder packetContent = new StringBuilder();
       for (int i = 0; i < receiveData.length; i++) {
         if (receiveData[i] == 0) {
           break;
         }
         packetContent.append((char) receiveData[i]); // 拼接设备名称
       }
       deviceName = packetContent.toString(); // 设备名称
       Device device = new Device();
       device.setDeviceName(deviceIp);
       device.setDeviceIp(deviceName);
       lists.add(device);
       if (deviceName.equals(deviceIp)) {
         // find server ip address:
         // deviceName
         break;
       } else {
         // not find server ip address,
         // continue …
         try {
           Thread.sleep(1000);
         } catch (InterruptedException e) {
         }
       }
     } catch (SocketTimeoutException e) {
       if (isDebug) {}
       listMulticasts.clear();
       listMulticasts.addAll(lists);
     }
     try {
       Thread.sleep(5000);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
   return deviceName;
 }