コード例 #1
0
  // Discovery thread
  @Override
  public void run() {

    while (!Thread.currentThread().isInterrupted()) {

      try {
        socket = new DatagramSocket(DISCOVERY_PORT, InetAddress.getByName("0.0.0.0"));
        socket.setBroadcast(true);

        // Keep an UDP Socket open
        while (!Thread.currentThread().isInterrupted() && socket.isBound()) {
          // Ready to receive sockets

          // Receive a packet
          byte[] rcvBuff = new byte[15000];
          DatagramPacket packet = new DatagramPacket(rcvBuff, rcvBuff.length);
          socket.receive(packet);

          // Packet received
          String msg = new String(packet.getData()).trim();
          if (msg.equals("REMOTECRAFT_DISCOVERY_REQUEST")) {
            // Attach world name
            String msgResponse =
                "REMOTECRAFT_DISCOVERY_RESPONSE:"
                    + String.valueOf(this.worldSeed)
                    + "_"
                    + this.worldName;
            byte[] sendData = msgResponse.getBytes();

            // Send response
            DatagramPacket sendPacket =
                new DatagramPacket(
                    sendData, sendData.length, packet.getAddress(), packet.getPort());
            if (socket.isBound()) {
              try {
                socket.send(sendPacket);
              } catch (Exception e) {
                e.printStackTrace();
              }
            } else {
              continue;
            }
          }
        }

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          socket.disconnect();
          socket.close();
        } catch (NullPointerException e) {
          e.printStackTrace();
        }
      }
    } // while !threadIsInterrupted
  }
コード例 #2
0
 public void run() {
   while (true) {
     try {
       DatagramSocket ds = new DatagramSocket(local_port);
       while (ds.isBound()) {
         Thread.sleep(50);
         // ds = new DatagramSocket(local_port);
       }
       DatagramPacket packin =
           new DatagramPacket(byte_packet1, byte_packet1.length, ia, getport);
       ds.send(packin);
       ds.close();
       Thread.sleep(5000);
     } catch (SocketException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
       // System.out.println(ex.getMessage());
     } catch (IOException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
     } catch (InterruptedException ex) {
       Logger.getLogger(myIP.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }