Esempio n. 1
0
 protected DatagramSocket createSocket(URI uri, InetAddress inetAddress) throws IOException {
   // SocketAddress sa = new InetSocketAddress(uri.getHost(),
   // uri.getPort());
   MulticastSocket socket = new MulticastSocket(uri.getPort());
   socket.joinGroup(inetAddress);
   return socket;
 }
Esempio n. 2
0
  /**
   * Connect the socket. Called by MIOPListener.
   *
   * @param profile
   * @param time_out unused, we use SO_TIMEOUT
   */
  @Override
  public void connect(Profile profile, long time_out) {
    if (!is_connected()) {
      if (profile instanceof MIOPProfile) {
        this.profile = (MIOPProfile) profile;
      } else {
        throw new org.omg.CORBA.BAD_PARAM(
            "attempt to connect an MIOP connection "
                + "to a non-MIOP profile: "
                + profile.getClass());
      }

      try {
        socket = new MulticastSocket(((MIOPProfile) profile).getUIPMCProfile().the_port);

        socket.setSoTimeout(socketTimeout);
        socket.setTimeToLive(timeToLive);
        socket.joinGroup(((MIOPProfile) profile).getGroupInetAddress());

        connection_info = socket.toString();
      } catch (Exception e) {
        if (socket != null) {
          socket.close();
        }
        throw new RuntimeException("Can't create multicast socket: " + profile);
      }

      connected = true;

      groupListener.start();
    }
  }
  @Override
  public int send(String mess) throws Exception, RemoteException, RemoteException {
    if (s == null) {
      try {
        group = InetAddress.getByName(config.getGroup());
        if (config.getHost() != null) {
          InetAddress addr = InetAddress.getByName(config.getHost());
          InetSocketAddress addrs = new InetSocketAddress(addr, config.getMultiport());
          s = new MulticastSocket(addrs);
        } else s = new MulticastSocket(config.getMultiport());

        s.setTimeToLive(config.getTtl());
        s.joinGroup(group);
      } catch (Exception ex) {
        log.error("Unable to use multicast: " + ex);
        s = null;
        return -1;
      }
    }

    byte[] buf;
    buf = mess.getBytes(US_ASCII);
    DatagramPacket data = new DatagramPacket(buf, buf.length, group, config.getMultiport());
    try {
      s.send(data);
    } catch (Exception ex) {
      log.error("Unable to send colllected load information: " + ex);
      s.close();
      s = null;
      return -1;
    }
    return 0;
  }
 private void createSocket() throws IOException {
   if (this.getTheSocket() == null) {
     MulticastSocket socket;
     if (this.isAcknowledge()) {
       if (logger.isDebugEnabled()) {
         logger.debug("Listening for acks on port: " + this.getAckPort());
       }
       if (localAddress == null) {
         socket = new MulticastSocket(this.getAckPort());
       } else {
         InetAddress whichNic = InetAddress.getByName(this.localAddress);
         socket = new MulticastSocket(new InetSocketAddress(whichNic, this.getAckPort()));
       }
       if (this.getSoReceiveBufferSize() > 0) {
         socket.setReceiveBufferSize(this.getSoReceiveBufferSize());
       }
     } else {
       socket = new MulticastSocket();
     }
     if (this.timeToLive >= 0) {
       socket.setTimeToLive(this.timeToLive);
     }
     setSocketAttributes(socket);
     if (localAddress != null) {
       InetAddress whichNic = InetAddress.getByName(this.localAddress);
       NetworkInterface intfce = NetworkInterface.getByInetAddress(whichNic);
       socket.setNetworkInterface(intfce);
     }
     this.setSocket(socket);
   }
 }
 /** {@inheritDoc} */
 public void run() {
   final int MULTICAST_PORT = configuration.getMulticastPort();
   final String MULTICAST_ADDRESS = configuration.getMulticastAddress();
   String multicastLocation = MULTICAST_ADDRESS + ":" + MULTICAST_PORT;
   MulticastSocket socket = null;
   InetAddress address = null;
   try {
     socket = new MulticastSocket(MULTICAST_PORT);
     address = InetAddress.getByName(MULTICAST_ADDRESS);
     logger.info("Created IP discover multicast server !");
   } catch (IOException e) {
     logger.error("Can't create multicast socket on " + multicastLocation, e);
   }
   try {
     socket.joinGroup(address);
     logger.info("Joined a group : " + multicastLocation);
   } catch (IOException e) {
     logger.error("Can't join group of " + multicastLocation, e);
   }
   byte[] buf = new byte[512];
   DatagramPacket packet = new DatagramPacket(buf, buf.length);
   while (true) {
     try {
       logger.info("Listening on  " + multicastLocation);
       socket.receive(packet);
       logger.info(
           "Received an IP auto-discovery request from " + packet.getAddress().getHostAddress());
     } catch (IOException e) {
       logger.error("Can't receive packet on " + MULTICAST_ADDRESS + ":" + MULTICAST_PORT, e);
     }
     sendLocalIPBack(packet);
   }
 }
Esempio n. 6
0
    public void run() {
      try {
        MulticastSocket socket = new MulticastSocket(UDP_SERVER_PORT);
        DatagramPacket packet;
        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        @SuppressWarnings("deprecation")
        String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        String partialIp = "";
        for (int j = ip.length() - 1; j > 0; j--) {
          if (ip.charAt(j) == '.') {
            partialIp = ip.substring(0, j + 1);
            break;
          }
        }
        for (int i = 2; i <= 255; i++) {
          String messageStr = "SAMMS6 Client";

          InetAddress sendingAddress =
              InetAddress.getByName(partialIp + Integer.toString(i)); // 127.0.0.1
          packet =
              new DatagramPacket(
                  messageStr.getBytes(), messageStr.length(), sendingAddress, UDP_SERVER_PORT);
          socket.send(packet);
        }
        socket.close();
      } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Esempio n. 7
0
    @Override
    protected String doInBackground(String... params) {
      WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
      if (wm != null) {
        MulticastLock mcLock = wm.createMulticastLock("SAAMS6");
        mcLock.acquire();
      }

      byte[] byteMessage = new byte[MAX_UDP_DATAGRAM_LEN];
      DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length);
      MulticastSocket socket = null;
      while (keepRunning) {
        try {
          socket = new MulticastSocket(UDP_SERVER_PORT);
          socket.receive(packet);
          String message = new String(byteMessage, 0, packet.getLength());

          if (message.equals("SAMMS6 Server")) {
            ServerIP = packet.getSocketAddress().toString();
            socket.close();
            keepRunning = false;
          }
        } catch (Throwable e) {
          e.printStackTrace();
        }
      }

      return ServerIP;
    }
Esempio n. 8
0
  /** Close this connection. */
  @Override
  public synchronized void close() {
    if (!connected) {
      return;
    }

    // Finish with the multicast socket
    try {
      socket.leaveGroup(((MIOPProfile) profile).getGroupInetAddress());
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) {
        logger.debug("Exception when closing the socket", ex);
      }
    }
    try {
      socket.close();

      // this will cause exceptions when trying to read from
      // the streams. Better than "nulling" them.
      if (in_stream != null) {
        in_stream.close();
      }
      if (out_stream != null) {
        out_stream.close();
      }
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) {
        logger.debug("Exception when closing the socket", ex);
      }
    }
    connected = false;
  }
Esempio n. 9
0
  void setBufferSizes() {
    if (sock != null) {
      try {
        sock.setSendBufferSize(ucast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_send_buf_size in sock: " + ex);
      }
      try {
        sock.setReceiveBufferSize(ucast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_recv_buf_size in sock: " + ex);
      }
    }

    if (mcast_sock != null) {
      try {
        mcast_sock.setSendBufferSize(mcast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_send_buf_size in mcast_sock: " + ex);
      }

      try {
        mcast_sock.setReceiveBufferSize(mcast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_recv_buf_size in mcast_sock: " + ex);
      }
    }
  }
Esempio n. 10
0
  /** Publish a request message to the specified multicast group. */
  protected void publishRequest(String message) throws IOException, SocketException {

    groupAddr = InetAddress.getByName(request_group);
    interfaceAddr = InetAddress.getByName(request_interface_address);

    /* is it a multicast address? */
    if (groupAddr.isMulticastAddress()) {

      /* open the socket and join the multicast group */
      udpSocket = new MulticastSocket();
      udpSocket.setNetworkInterface(NetworkInterface.getByInetAddress(interfaceAddr));
      udpSocket.setInterface(interfaceAddr);
      udpSocket.joinGroup(groupAddr);

      /* Send request packet */
      DatagramPacket p =
          new DatagramPacket(message.getBytes(), message.getBytes().length, groupAddr, 7777);

      System.out.println("Sending request: " + new String(p.getData(), 0, p.getLength()));
      udpSocket.send(p);

    } else {
      System.err.println("Invalid multicast address: " + groupAddr.toString());
    }
  }
Esempio n. 11
0
  public Main(daemon.Daemon masterTask) {
    try {
      // Find out own ip
      InetAddress ownAddress = InetAddress.getLocalHost();
      ip = ownAddress.getHostAddress();
      this.logger.info("I'm node with ip {} and i'm joining the multicast group", this.ip);

      // Join multicast group
      ms = new MulticastSocket(this.port);
      ms.setSoTimeout(5000);
      group = InetAddress.getByName(this.groupIp);
      ms.joinGroup(group);

      // Create thread of master task
      this.masterTaskRunnable = masterTask;
      this.masterTask = new Thread(this.masterTaskRunnable);

      Thread.sleep(2000L);
    } catch (UnknownHostException e) {
      this.logger.error("Cannot get you local ip address");
    } catch (IOException e) {
      this.logger.error("Error joining node to group");
    } catch (Exception e) {
      this.logger.error("Error pausing thread");
    }
  }
Esempio n. 12
0
    /** Main processing method which handles received datagrams. */
    public void run() {
      isRunning = true;

      while (isRunning) {
        try {
          /* TODO confirm packet size is appropriate */
          byte[] buf = new byte[256];
          DatagramPacket p = new DatagramPacket(buf, buf.length);

          try {
            if (!udpListenRequestSocket.isClosed()) {
                /* if socket not already closed */
              udpListenRequestSocket.receive(p);

              /* get the packet as a string */
              listenPayload = new String(p.getData(), 0, p.getLength());

              /* add unique payloads - subclass responsibility to identify valid responses */
              if (!responses.contains(listenPayload)) {
                responses.add(p);
              }
            }

          } catch (SocketTimeoutException e) {
            // TODO what happens if we don't hear from anybody?
          }
        } catch (IOException e) {
          if (!udpListenRequestSocket.isClosed()) {
            e.printStackTrace();
          }
          /* stop looping */
          break;
        }
      }
    }
Esempio n. 13
0
  /** {@inheritDoc} */
  public void run() {

    while (!isTerminate()) {

      byte[] buf = new byte[ServiceConstants.DATAGRAM_LENGTH];
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      setReceivedDatagramPacket(packet);

      try {

        MulticastSocket socket = getMulticastSocket();
        if (socket != null) {

          socket.receive(packet);
          if (isReplyPacket()) {

            ServiceDescription sd = getServiceDescription();
            if (sd != null) {

              fireDiscoverEvent(sd);
            }
          }
        }

      } catch (SocketTimeoutException ex) {
      } catch (IOException ex) {

        System.err.println("Unexpected exception: " + ex);
      }

      sendQueuedPacket();
    }
  }
Esempio n. 14
0
  /** {@inheritDoc} */
  public void start() {

    setTerminate(false);
    try {

      setMulticastInetAddress(InetAddress.getByName(ServiceConstants.MULTICAST_INET_ADDRESS));
      setMulticastPort(ServiceConstants.MULTICAST_PORT);

      MulticastSocket socket = new MulticastSocket(getMulticastPort());
      socket.joinGroup(getMulticastInetAddress());
      socket.setSoTimeout(ServiceConstants.BROWSER_SOCKET_TIMEOUT);
      setMulticastSocket(socket);
      startLookup();

    } catch (UnknownHostException uhe) {

      System.err.println("Unexpected exception: " + uhe);
      uhe.printStackTrace();
      setTerminate(true);

    } catch (IOException ex) {

      System.err.println("Unexpected exception: " + ex);
      ex.printStackTrace();
      setTerminate(true);
    }
  }
Esempio n. 15
0
  @Override
  public void run() {
    if (!Thread.currentThread().getName().equals("DiscoveryListener daemon")) {
      throw new RuntimeException("No right to call this method");
    }
    inService = true;
    while (inService) {
      try {
        listenBroadCast();
      } catch (SocketTimeoutException ex) {
        // ignoring
      } catch (IOException ioEx) {
        ioEx.printStackTrace();
      } catch (Exception ex) {
        ex.printStackTrace();
        inService = false;
      }
    }

    try {
      skt.leaveGroup(InetAddress.getByName(Discovery.SSDP_IP));
      skt.close();
    } catch (Exception ex) {
      // ignoring
    }
  }
Esempio n. 16
0
  /** Creates a new socket, cleaning up if anything goes wrong in the process */
  private MulticastSocket createMulticastSocket(String label, InetAddress intf, int port)
      throws Exception {
    MulticastSocket socket = null;

    try {
      _logger.info(
          "Preparing {} socket. interface:{}, port:{}, group:{}",
          label,
          (intf == null ? "default" : intf),
          (port == 0 ? "any" : port),
          _group);

      // in previous versions the interface was selected using constructor instead of
      // 'socket.setInterface(intf)'
      // but that uncovered side-effect in OSX which caused 'cannot assign address' Java bug

      socket = new MulticastSocket(port); // (port '0' means any port)

      if (intf != null) socket.setInterface(intf);

      // join the multicast group
      socket.joinGroup(_group);

      _logger.info("{} ready. localAddr:{}", label, socket.getLocalSocketAddress());

      return socket;

    } catch (Exception exc) {
      Stream.safeClose(socket);

      throw exc;
    }
  }
Esempio n. 17
0
 /** Leave multicast group and close the multicast socket. */
 public void close() {
   try {
     multicastSocket.leaveGroup(group);
     multicastSocket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  @Scheduled(fixedDelay = Integer.MAX_VALUE)
  public void startListening() {

    if (disable) {
      return;
    }

    log.info("Starting UPNP Discovery Listener");

    try (DatagramSocket responseSocket = new DatagramSocket(upnpResponsePort);
        MulticastSocket upnpMulticastSocket = new MulticastSocket(UPNP_DISCOVERY_PORT); ) {
      InetSocketAddress socketAddress =
          new InetSocketAddress(UPNP_MULTICAST_ADDRESS, UPNP_DISCOVERY_PORT);
      Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();

      while (ifs.hasMoreElements()) {
        NetworkInterface xface = ifs.nextElement();
        Enumeration<InetAddress> addrs = xface.getInetAddresses();
        String name = xface.getName();
        int IPsPerNic = 0;

        while (addrs.hasMoreElements()) {
          InetAddress addr = addrs.nextElement();
          log.debug(name + " ... has addr " + addr);
          if (InetAddressUtils.isIPv4Address(addr.getHostAddress())) {
            IPsPerNic++;
          }
        }
        log.debug("Checking " + name + " to our interface set");
        if (IPsPerNic > 0) {
          upnpMulticastSocket.joinGroup(socketAddress, xface);
          log.debug("Adding " + name + " to our interface set");
        }
      }

      while (true) { // trigger shutdown here
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        upnpMulticastSocket.receive(packet);
        String packetString = new String(packet.getData());
        if (isSSDPDiscovery(packetString)) {
          log.debug(
              "Got SSDP Discovery packet from "
                  + packet.getAddress().getHostAddress()
                  + ":"
                  + packet.getPort());
          sendUpnpResponse(responseSocket, packet.getAddress(), packet.getPort());
        }
      }

    } catch (IOException e) {
      log.error("UpnpListener encountered an error. Shutting down", e);
      ConfigurableApplicationContext context =
          (ConfigurableApplicationContext) UpnpListener.this.applicationContext;
      context.close();
    }
    log.info("UPNP Discovery Listener Stopped");
  }
  public void sendFrame(final Frame frame) throws IOException {

    final byte[] message = toValidMessage(frame);
    final DatagramPacket packet =
        new DatagramPacket(message, 0, message.length, mcastAddress, mcastPort);
    for (final MulticastSocket mcastSocket : mcastSockets) {
      mcastSocket.send(packet);
    }
  }
  public MulticastOSCReceiver(MulticastSocket ms, String group, int port) throws IOException {
    super(
        OSCPacketCodec.getDefaultCodec(),
        UDP,
        new InetSocketAddress(ms.getLocalAddress(), ms.getLocalPort()),
        false);

    this.ms = ms;
  }
  /**
   * Sends a leave message to the multicast group and leaves it. The <CODE>DiscoveryResponder</CODE>
   * leaves its multicast group. This method has no effect if the <CODE>DiscoveryResponder</CODE> is
   * <CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   */
  public void stop() {
    if (state == ONLINE) {
      changeState(STOPPING);
      // ------------------------
      // Stop corresponding thread
      // ------------------------

      responder.stopRequested = true;

      synchronized (responder.interrupted) {
        if (!responder.interrupted.booleanValue()) {
          responderThread.interrupt();
        }
      }

      // Fix for cases when the interrupt does not work (Windows NT)
      try {
        MulticastSocket ms = new MulticastSocket(multicastPort);

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          ms.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("stop ", "use the interface " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        InetAddress group = InetAddress.getByName(multicastGroup);
        ms.joinGroup(group);
        ms.send(new DatagramPacket(new byte[1], 1, group, multicastPort));
        ms.leaveGroup(group);
      } catch (Exception e) {
        if (logger.finerOn()) {
          logger.finer(
              "stop ",
              "Unexpected exception occurred trying to send empty message " + e.getMessage());
        }
      }

      // ------------------------
      // free 'remained' allocated resource
      // ------------------------
      responder = null;
      System.runFinalization();

      // ----------------
      // Update state
      // ----------------
      // changeState(OFFLINE) ;
    } else {
      if (logger.finerOn()) {
        logger.finer("stop ", "Responder is not ONLINE");
      }
    }
  }
 @Test
 public void verifySendMulticast() throws Exception {
   MulticastSocket socket;
   try {
     socket = new MulticastSocket();
   } catch (Exception e) {
     return;
   }
   final int testPort = socket.getLocalPort();
   final String multicastAddress = this.multicastRule.getGroup();
   final String payload = "foo";
   final CountDownLatch listening = new CountDownLatch(2);
   final CountDownLatch received = new CountDownLatch(2);
   Runnable catcher =
       new Runnable() {
         @Override
         public void run() {
           try {
             byte[] buffer = new byte[8];
             DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
             MulticastSocket socket = new MulticastSocket(testPort);
             socket.setInterface(InetAddress.getByName(multicastRule.getNic()));
             InetAddress group = InetAddress.getByName(multicastAddress);
             socket.joinGroup(group);
             listening.countDown();
             LogFactory.getLog(getClass())
                 .debug(Thread.currentThread().getName() + " waiting for packet");
             socket.receive(receivedPacket);
             socket.close();
             byte[] src = receivedPacket.getData();
             int length = receivedPacket.getLength();
             int offset = receivedPacket.getOffset();
             byte[] dest = new byte[length];
             System.arraycopy(src, offset, dest, 0, length);
             assertEquals(payload, new String(dest));
             LogFactory.getLog(getClass())
                 .debug(Thread.currentThread().getName() + " received packet");
             received.countDown();
           } catch (Exception e) {
             listening.countDown();
             e.printStackTrace();
           }
         }
       };
   Executor executor = Executors.newFixedThreadPool(2);
   executor.execute(catcher);
   executor.execute(catcher);
   assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
   MulticastSendingMessageHandler handler =
       new MulticastSendingMessageHandler(multicastAddress, testPort);
   handler.setLocalAddress(this.multicastRule.getNic());
   handler.handleMessage(MessageBuilder.withPayload(payload).build());
   assertTrue(received.await(10000, TimeUnit.MILLISECONDS));
   handler.stop();
   socket.close();
 }
Esempio n. 23
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;
 }
Esempio n. 24
0
 public void leaveGroupe() {
   try {
     multicastSocket.leaveGroup(InetAddress.getByName(adresse));
   } catch (UnknownHostException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   multicastSocket.close();
 }
 /**
  * Start.
  *
  * @throws IOException
  */
 final void init() throws IOException {
   socket = new MulticastSocket(groupMulticastPort.intValue());
   if (hostAddress != null) {
     socket.setInterface(hostAddress);
   }
   socket.joinGroup(groupMulticastAddress);
   receiverThread = new MulticastReceiverThread();
   receiverThread.start();
   processingThreadPool = Executors.newCachedThreadPool();
 }
Esempio n. 26
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;
 }
Esempio n. 27
0
  protected void receiveAndTestResults() throws Exception {
    s2.setSoTimeout(2000);
    for (int i = 0; i < 100; i++) {

      DatagramPacket packet = new DatagramPacket(new byte[32], 32, inet, uri.getPort());

      s2.receive(packet);
      UdpMessageAdapter adapter = new UdpMessageAdapter(packet);
      System.out.println("Received message: " + adapter.getPayloadAsString());
    }
    Thread.sleep(3000);
  }
Esempio n. 28
0
  public MulticastServer(String interfaceAddress) {
    try {
      multicastSocket = new MulticastSocket(Globals.MULTICAST_PORT);
      group = InetAddress.getByName(Globals.MULTICAST_ADDRESS);

      multicastSocket.setInterface(InetAddress.getByName(interfaceAddress));
      multicastSocket.joinGroup(group);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args) throws Exception {
   InetAddress addr = InetAddress.getByName("230.0.0.1");
   MulticastSocket soc = new MulticastSocket(2056);
   soc.joinGroup(addr);
   DatagramPacket dp = new DatagramPacket(new byte[80], 80);
   for (int i = 0; i < 5; i++) {
     soc.receive(dp);
     String msg = new String(dp.getData(), 0, dp.getLength());
     System.out.println(msg);
   }
   soc.leaveGroup(addr);
   soc.close();
 }
Esempio n. 30
0
 // @java.lang.Override
 public void destroyObject(Object key, Object object) throws Exception {
   ImmutableEndpoint ep = (ImmutableEndpoint) key;
   InetAddress inetAddress;
   String host = ep.getEndpointURI().getHost();
   if ("null".equalsIgnoreCase(host)) {
     inetAddress = InetAddress.getLocalHost();
   } else {
     inetAddress = InetAddress.getByName(host);
   }
   MulticastSocket socket = (MulticastSocket) object;
   socket.leaveGroup(inetAddress);
   super.destroyObject(key, object);
 }