コード例 #1
0
  protected void doTearDown() throws Exception {
    try {
      s1.close();
    } catch (Exception e) {
      // ignore
    }
    try {
      s2.close();
    } catch (Exception e) {
      // ignore
    }

    super.doTearDown();
  }
コード例 #2
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();
      }
    }
コード例 #3
0
ファイル: Basic.java プロジェクト: OS2World/LIB-JAVA-OpenJDK
  void MulticastSocketTests() throws Exception {
    test("Check SO_REUSEADDR is enabled in MulticastSocket()");
    MulticastSocket s1 = new MulticastSocket();
    check(s1.getReuseAddress());
    s1.close();

    test("Check that SO_REUSEADDR is not disabled by " + "MulticastSocket.bind()");

    s1 = new MulticastSocket(null);

    // bind to specific address
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), 0);
    s1.bind(isa);
    check(s1.getReuseAddress());
    s1.close();
  }
コード例 #4
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
    }
  }
コード例 #5
0
ファイル: AbstractSeeker.java プロジェクト: destenson/gaiandb
    /** Stop listening. */
    public void stop() {
      isRunning = false;

      if (udpListenRequestSocket != null) {
        udpListenRequestSocket.close();
      }
    }
コード例 #6
0
  @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;
  }
コード例 #7
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;
  }
コード例 #8
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;
    }
コード例 #9
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();
    }
  }
コード例 #10
0
 /** Leave multicast group and close the multicast socket. */
 public void close() {
   try {
     multicastSocket.leaveGroup(group);
     multicastSocket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #11
0
ファイル: AbstractSeeker.java プロジェクト: destenson/gaiandb
  /**
   * Shutdown the listening and publishing resources used for the discovery, as appropriate.
   *
   * @param grl
   */
  protected void cleanupResources(DiscoveryListener grl) {
    if (grl != null) { // stop listener
      grl.stop();
    }

    if (udpSocket != null) {
      udpSocket.close();
    }
  }
コード例 #12
0
 protected void closeChannel() throws IOException {
   if (ms != null) {
     try {
       ms.close();
     } finally {
       ms = null;
     }
   }
 }
 @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();
 }
コード例 #14
0
 public void leaveGroupe() {
   try {
     multicastSocket.leaveGroup(InetAddress.getByName(adresse));
   } catch (UnknownHostException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   multicastSocket.close();
 }
コード例 #15
0
 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();
 }
コード例 #16
0
  @Before
  public void assumeMulticast() throws Exception {
    InetAddress multicastAddress = InetAddress.getByName("239.255.0.1");

    // Make sure receiver is setup before the sender, otherwise the packet gets lost
    MulticastSocket receiver = new MulticastSocket(0);
    receiver.joinGroup(multicastAddress);

    MulticastSocket sender = new MulticastSocket();
    sender.setTimeToLive(1);
    sender.send(
        new DatagramPacket(new byte[] {1}, 0, 1, multicastAddress, receiver.getLocalPort()));
    sender.close();

    byte[] buffer = new byte[1];
    receiver.setSoTimeout(1000);
    try {
      receiver.receive(new DatagramPacket(buffer, 0, buffer.length));
    } catch (SocketTimeoutException x) {
      Assume.assumeNoException(x);
    } finally {
      receiver.close();
    }
  }
コード例 #17
0
 public synchronized void shutdown() {
   active = false;
   if (advertiseViaMulticastDNS) {
     zeroConf.unadvertise();
   }
   if (handlerThread != null) {
     handlerThread.interrupt();
   }
   if (receiverThread != null) {
     receiverThread.interrupt();
   }
   if (socket != null) {
     socket.close();
   }
 }
コード例 #18
0
 public void stop() {
   try {
     if (!running && multicastSocket.isClosed()) {
       return;
     }
     try {
       multicastSocket.close();
     } catch (Throwable ignored) {
     }
     running = false;
     if (!stopLatch.await(5, TimeUnit.SECONDS)) {
       logger.warning("Failed to shutdown MulticastService in 5 seconds!");
     }
   } catch (Throwable e) {
     logger.warning(e);
   }
 }
コード例 #19
0
ファイル: MulticastSender.java プロジェクト: mikeb01/scratch
  public static void main(final String[] args) throws Exception {
    //        System.setProperty("java.net.preferIPv4Stack", "true");

    if (2 != args.length && 3 != args.length) {
      System.out.println(
          "Usage: java MulticastSender <multicast address> <number of messages> [interface]");
      return;
    }

    final String address = args[0];

    final long count = Long.parseLong(args[1]);

    final int port = 4445;
    final int serverPort = 4447;

    final byte[] buffer = "This is a test string with sufficient data to send".getBytes("ASCII");

    final InetAddress group = InetAddress.getByName(address);
    MulticastSocket socket;

    if (3 == args.length) {
      final String interfaceAddress = args[2];
      System.out.println("Binding to interface: " + interfaceAddress);
      socket = new MulticastSocket(new InetSocketAddress(interfaceAddress, serverPort));
    } else {
      socket = new MulticastSocket(serverPort);
    }

    final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);

    final MulticastSender sender = new MulticastSender();
    final Thread t = new Thread(sender);
    t.setDaemon(true);
    t.start();

    for (long i = count; --i != 0; ) {
      packet.setData(buffer);
      socket.send(packet);
      sender.messageCounter++;
    }

    Thread.sleep(1000);

    socket.close();
  }
コード例 #20
0
 public boolean send(String msg, String bindAddr, int bindPort) {
   try {
     MulticastSocket msock;
     if ((bindAddr) != null && (0 < bindPort)) {
       msock = new MulticastSocket(null);
       msock.bind(new InetSocketAddress(bindAddr, bindPort));
     } else msock = new MulticastSocket();
     DatagramPacket dgmPacket = new DatagramPacket(msg.getBytes(), msg.length(), ssdpMultiGroup);
     // Thnaks for Tho Beisch (11/09/04)
     msock.setTimeToLive(4);
     msock.send(dgmPacket);
     msock.close();
   } catch (Exception e) {
     Debug.warning(e);
     return false;
   }
   return true;
 }
コード例 #21
0
ファイル: UDP.java プロジェクト: NZDIS/jgroups
 void closeMulticastSocket() {
   if (mcast_sock != null) {
     try {
       if (mcast_addr != null) {
         // by sending a dummy packet the thread will be awakened
         sendDummyPacket(mcast_addr.getIpAddress(), mcast_addr.getPort());
         Util.sleep(300);
         mcast_sock.leaveGroup(mcast_addr.getIpAddress());
       }
       mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop
       mcast_sock = null;
       if (Trace.trace) {
         Trace.info("UDP.closeMulticastSocket()", "multicast socket closed");
       }
     } catch (IOException ex) {
     }
     mcast_addr = null;
   }
 }
コード例 #22
0
  public OioDatagramChannel(Integer id, MulticastSocket socket) {
    super(null, id);

    boolean success = false;
    try {
      socket.setSoTimeout(SO_TIMEOUT);
      socket.setBroadcast(false);
      success = true;
    } catch (SocketException e) {
      throw new ChannelException("Failed to configure the datagram socket timeout.", e);
    } finally {
      if (!success) {
        socket.close();
      }
    }

    this.socket = socket;
    config = new DefaultDatagramChannelConfig(socket);
  }
コード例 #23
0
  @Override
  protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress)
      throws Exception {
    if (localAddress != null) {
      socket.bind(localAddress);
    }

    boolean success = false;
    try {
      socket.connect(remoteAddress);
      success = true;
    } finally {
      if (!success) {
        try {
          socket.close();
        } catch (Throwable t) {
          logger.warn("Failed to close a socket.", t);
        }
      }
    }
  }
コード例 #24
0
  public static void main(String[] args) throws IOException {

    MulticastSocket socket = new MulticastSocket(4446);
    InetAddress address = InetAddress.getByName("230.0.0.1");
    socket.joinGroup(address);

    DatagramPacket packet;

    // get a few quotes
    for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("Quote of the Moment: " + received);
    }

    socket.leaveGroup(address);
    socket.close();
  }
コード例 #25
0
  public void updatePeers(Integer processId, Integer transactionId) {
    MulticastSocket socket = null;
    try {
      socket = new MulticastSocket(multicastPort);
      byte[] buf = new byte[256];
      // don't wait for request...just send a quote

      String dString = processId.toString() + ":" + transactionId.toString();
      buf = dString.getBytes();

      InetAddress group = InetAddress.getByName(multicastAddress);
      DatagramPacket packet;
      packet = new DatagramPacket(buf, buf.length, group, multicastPort);
      socket.send(packet);

    } catch (IOException e) {
      e.printStackTrace();

    } finally {
      if (socket != null) socket.close();
    }
  }
コード例 #26
0
  public void listenMulticast() throws IOException, InterruptedException {
    MulticastSocket socket = new MulticastSocket(multicastPort);
    InetAddress group = InetAddress.getByName(multicastAddress);
    socket.joinGroup(group);

    DatagramPacket packet;
    while (true) {
      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);
      String received = new String(packet.getData()).trim();
      String[] data = received.split(":");
      if (Integer.parseInt(data[0]) == this.id) {
        consecutiveReceptions++;
      } else {
        consecutiveReceptions = 0;
      }

      if (ProcIdLastTimeMap.containsKey(this.id.toString())) {
        if (System.currentTimeMillis() - ProcIdLastTimeMap.get(id.toString())
            < peersUpdateInterval + 1) {
          updatePeers(id, 0);
          sleep(peersUpdateInterval);
        }
      }

      ProcIdTransIdMap.put(data[0], data[1]);
      ProcIdLastTimeMap.put(data[0], System.currentTimeMillis());

      // System.out.println("MulticastReceived: " + received);
      if (shouldBeRunning()) {
        break;
      }
    }

    socket.leaveGroup(group);
    socket.close();
  }
コード例 #27
0
 public void exit() {
   stop();
   socket.close();
 }
  @Test
  public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;
    try {
      socket = new MulticastSocket();
    } catch (Exception e) {
      return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher =
        new Runnable() {
          @Override
          public void run() {
            try {
              byte[] buffer = new byte[1000];
              DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
              MulticastSocket socket = new MulticastSocket(testPort);
              socket.setInterface(InetAddress.getByName(multicastRule.getNic()));
              socket.setSoTimeout(8000);
              InetAddress group = InetAddress.getByName(multicastAddress);
              socket.joinGroup(group);
              listening.countDown();
              assertTrue(ackListening.await(10, TimeUnit.SECONDS));
              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[6];
              System.arraycopy(src, offset + length - 6, dest, 0, 6);
              assertEquals(payload, new String(dest));
              LogFactory.getLog(getClass())
                  .debug(Thread.currentThread().getName() + " received packet");
              DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
              mapper.setAcknowledge(true);
              mapper.setLengthCheck(true);
              Message<byte[]> message = mapper.toMessage(receivedPacket);
              Object id = message.getHeaders().get(IpHeaders.ACK_ID);
              byte[] ack = id.toString().getBytes();
              DatagramPacket ackPack =
                  new DatagramPacket(
                      ack,
                      ack.length,
                      new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
              DatagramSocket out = new DatagramSocket();
              out.send(ackPack);
              LogFactory.getLog(getClass())
                  .debug(
                      Thread.currentThread().getName()
                          + " sent ack to "
                          + ackPack.getSocketAddress());
              out.close();
              ackSent.countDown();
              socket.close();
            } 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, true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
  }
コード例 #29
0
 public void close() {
   usock.close();
 }
コード例 #30
0
 public void disconnect() throws Exception {
   if (connection != null) connection.close();
   allreadyTried = false;
   connection = null;
 }