Example #1
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);
    }
  }
Example #2
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");
    }
  }
Example #3
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();
    }
  }
Example #4
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;
 }
Example #5
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);
  }
  @Override
  public void run() {
    try {
      mReceiveSocket = new MulticastSocket(Search.MULTICAST_RECEIVE_PORT);
      mReceiveSocket.setSoTimeout(Search.TIME_OUT);
      mMulticastAddress = InetAddress.getByName(Search.MULTICAST_IP);
    } catch (Exception e) {
      Log.e(TAG, "Create mReceiveSocket fail." + e);
    }

    join(mMulticastAddress);
    startListenServerMessage();
  }
Example #7
0
 /**
  * Broadcasts a SSDP discovery message into the network to find provided services.
  *
  * @return The Socket the answers will arrive at.
  * @throws UnknownHostException
  * @throws IOException
  * @throws SocketException
  * @throws UnsupportedEncodingException
  */
 private MulticastSocket sendDiscoveryBroacast()
     throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
   InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
   final int port = 1900;
   MulticastSocket socket = new MulticastSocket(port);
   socket.setReuseAddress(true);
   socket.setSoTimeout(130000);
   socket.joinGroup(multicastAddress);
   byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
   DatagramPacket datagramPacket =
       new DatagramPacket(requestMessage, requestMessage.length, multicastAddress, port);
   socket.send(datagramPacket);
   return socket;
 }
Example #8
0
 /*
  * (non-Javadoc)
  *
  * @see org.jacorb.orb.etf.ConnectionBase#setTimeout(int)
  */
 @Override
 protected void setTimeout(int timeout) {
   if (socket != null) {
     try {
       if (logger.isInfoEnabled()) {
         logger.info("Socket timeout set to " + timeout + " ms");
       }
       socket.setSoTimeout(timeout);
     } catch (SocketException se) {
       if (logger.isInfoEnabled()) {
         logger.info("SocketException", se);
       }
     }
   }
 }
Example #9
0
 /**
  * Scans all messages that arrive on the socket and scans them for the search keywords. The search
  * is not case sensitive.
  *
  * @param socket The socket where the answers arrive.
  * @param keywords The keywords to be searched for.
  * @return
  * @throws IOException
  */
 private String scanResposesForKeywords(MulticastSocket socket, String... keywords)
     throws IOException {
   // In the worst case a SocketTimeoutException raises
   socket.setSoTimeout(2000);
   do {
     logger.debug("Got an answer message.");
     byte[] rxbuf = new byte[8192];
     DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length);
     socket.receive(packet);
     String foundIp = analyzePacket(packet, keywords);
     if (foundIp != null) {
       return foundIp;
     }
   } while (true);
 }
Example #10
0
  private void startMultiCastSocket() throws IOException {
    int bindPort = Discovery.DEFAULT_SSDP_SEARCH_PORT;
    String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort");
    if (port != null) {
      bindPort = Integer.parseInt(port);
    }

    skt = new java.net.MulticastSocket(null);
    skt.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), bindPort));
    skt.setTimeToLive(Discovery.DEFAULT_TTL);
    skt.setSoTimeout(DEFAULT_TIMEOUT);
    skt.joinGroup(InetAddress.getByName(Discovery.SSDP_IP));

    byte[] buf = new byte[2048];
    input = new DatagramPacket(buf, buf.length);
  }
Example #11
0
 public Multicast(String ip, int port) {
   this.port = port;
   this.ip = ip;
   this.id = 0;
   this.nextId = 0;
   this.prevId = 0;
   nodes = new TreeMap<Integer, String>();
   try {
     mcsocket = new MulticastSocket(mcport);
     mcsocket.setSoTimeout(10000);
     mcsocket.joinGroup(InetAddress.getByName(mcgroup));
   } catch (IOException e) {
     System.out.println("Problem joining multicast group");
     e.printStackTrace();
   }
 }
Example #12
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);
  }
  @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();
    }
  }
Example #14
0
  private void handleMulticastInit(MulticastInitEvent e) {

    log.debug(":handleAppiaMulticastInit");

    if (!multicastReaders.containsKey(e.ipMulticast)) {
      /*creates a multicast socket and binds it to a specific port on the local host machine*/
      try {
        MulticastSocket multicastSock =
            new MulticastSocket(((InetSocketAddress) e.ipMulticast).getPort());

        log.debug(":handleAppiaMulticastInit: Socket Multicast created. Address: " + e.ipMulticast);

        /*joins a multicast group*/
        multicastSock.joinGroup(((InetSocketAddress) e.ipMulticast).getAddress());

        // keeping the multicast address...
        ipMulticast =
            new InetSocketAddress(
                ((InetSocketAddress) e.ipMulticast).getAddress(),
                ((InetSocketAddress) e.ipMulticast).getPort());

        log.debug(":handleAppiaMulticastInit: Socket Multicast joined.");

        try {
          multicastSock.setSoTimeout(param_SOTIMEOUT);
        } catch (SocketException se) {
          System.err.println(
              "Unable to set SoTimeout value on UdpSimpleSession. Using default OS value.");
          se.printStackTrace();
        }

        /* The socket is binded. Launch reader and return the event.*/
        final UdpSimpleReader multicastReader =
            new UdpSimpleReader(this, multicastSock, ipMulticast, e.fullDuplex ? null : myAddress);
        final Thread thread =
            e.getChannel()
                .getThreadFactory()
                .newThread(multicastReader, "MulticastReaderThread [" + ipMulticast + "]");
        multicastReader.setParentThread(thread);
        thread.start();

        multicastReaders.put(ipMulticast, multicastReader);

        /*forwarding the event*/
        e.error = false;
      } catch (IOException ex) {
        ex.printStackTrace();
        System.err.println("Error creating/joining the multicast socket");
        e.error = true;
      }
    } else {
      log.debug(":handleAppiaMulticastInit: Requested multicast socket already existed.");
    }

    try {
      e.setDir(Direction.invert(e.getDir()));
      e.setSource(this);
      e.init();
      e.go();
      log.debug(":handleAppiaMulticastInit: Returning multicastInit with error code: " + e.error);
      log.debug(
          ":handleAppiaMulticastInit: Direction is "
              + (e.getDir() == Direction.DOWN ? "DOWN" : "UP"));
    } catch (AppiaEventException ex) {
      ex.printStackTrace();
    }
  }
  public void run() {
    ChunkManager chunkManager = di.getChunkManager();

    if (!chunkManager.hasChunk(fileId, chunkNo)) {
      return;
    }

    byte[] chunkData = chunkManager.getChunk(fileId, chunkNo);
    byte[] message = createMessage(chunkData);

    // Wait Random Delay
    int randWait = (new Random()).nextInt(400);

    // Check Network, for repeat packets
    Channels channels = di.getChannels();
    String address = channels.getMDR().getAddress();
    Integer port = channels.getMDR().getPort();

    InetAddress group = null;
    MulticastSocket socket = null;
    try {
      group = InetAddress.getByName(address);
      socket = new MulticastSocket(port);
      socket.joinGroup(group);
    } catch (IOException e) {
      return;
    }

    try {
      byte[] buf = new byte[Constants.chunkSize + 2048];
      DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
      socket.setSoTimeout(randWait);
      socket.receive(packet);

      byte[] data = new byte[packet.getLength()];
      System.arraycopy(packet.getData(), 0, data, 0, packet.getLength());

      // System.out.println("Some Chunk");
      // System.out.println(Constants.getNElementFromMessage(data,0));
      // System.out.println(Constants.getNElementFromMessage(data,1));
      // System.out.println(fileId);
      // System.out.println(Constants.getNElementFromMessage(data,2));
      // System.out.println(chunkNo.toString());

      // Check if it's the same packet
      if (Constants.getNElementFromMessage(data, 0).equals("CHUNK")
          && Constants.getNElementFromMessage(data, 2).equals(fileId)
          && Constants.getNElementFromMessage(data, 3).equals(chunkNo.toString())) {
        System.out.println("Dont send Chunk. Someone already sent.");
        return;
      }
    } catch (IOException ignored) {
    }

    // Send
    try {
      DatagramPacket packet = new DatagramPacket(message, message.length, group, port);
      socket.send(packet);
      System.out.println("Sent CHUNK");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #16
0
  public void getPacket() {
    try {
      byte[] buffer = new byte[256];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

      try {
        listener.setSoTimeout(timeout);
        listener.receive(packet);
        numPacketsReceived++;
        waveManager.userInterface.updateNumPacketsReceived(numPacketsReceived);
      } catch (Exception e) {
      }

      byte[] message = packet.getData();
      int length = packet.getLength();

      String str = new String(message, 0, length);
      String[] strings = str.split("/");

      String fromCarID = strings[0];
      String messageID = strings[1];
      String fromGroup = strings[2];
      int hopCount = Integer.parseInt(strings[3]);
      String messageGroup = strings[4];
      int heading = Integer.parseInt(strings[5]);
      int vehicleSpeed = Integer.parseInt(strings[6]);
      double vehicleLattitude = Double.parseDouble(strings[7]);
      double vehicleLongitude = Double.parseDouble(strings[8]);

      // Commented for testing purposes
      // if(!(strings[0].equals(waveManager.CarID))){
      if (fromCarID.equals(waveManager.CarID)) {
        if (receivedMessagePreviously(fromCarID, messageID, messageGroup)) {

          // The order of these is where PRIORITIES take place
          if (fromGroup.equals(emergencyService.serviceGroup)) {
            output =
                "+ Received *EmergencyService* messageID '"
                    + messageID
                    + "' from CarID:'"
                    + fromCarID
                    + "': Sirens 'On', Heading:'"
                    + heading
                    + "', Speed: "
                    + vehicleSpeed
                    + " km/h, HopCount = "
                    + hopCount;
            waveManager.userInterface.output(output);

            emergencyService.computeData(heading, vehicleLattitude, vehicleLongitude);
          } else if (fromGroup.equals(brakeService.serviceGroup)) {
            int brakeAmount = Integer.parseInt(strings[9]);

            output =
                "+ Received *BrakeService* messageID '"
                    + messageID
                    + "' from CarID:'"
                    + fromCarID
                    + "': Speed: "
                    + vehicleSpeed
                    + " km/h, BrakeAmount: "
                    + brakeAmount
                    + "%, Lattitude:'"
                    + vehicleLattitude
                    + "' Longitude:'"
                    + vehicleLongitude
                    + "', Heading:'"
                    + heading
                    + "', HopCount = "
                    + hopCount;
            waveManager.userInterface.output(output);

            brakeService.computeData(
                fromCarID, heading, vehicleSpeed, vehicleLattitude, vehicleLongitude, brakeAmount);
          } else if (fromGroup.equals(generalInfoService.serviceGroup)) {
            output =
                "+ Received *GeneralInfoService* messageID '"
                    + messageID
                    + "' from CarID:'"
                    + fromCarID
                    + "': Speed:'"
                    + vehicleSpeed
                    + " km/h, Lattitude:'"
                    + vehicleLattitude
                    + "' Longitude:'"
                    + vehicleLongitude
                    + "', Heading:'"
                    + heading
                    + "', HopCount = "
                    + hopCount;
            waveManager.userInterface.output(output);

            generalInfoService.computeData(
                fromCarID, heading, vehicleSpeed, vehicleLattitude, vehicleLongitude);
          } else if (fromGroup.equals(trafficService.serviceGroup)) {

            int directionCluster = Integer.parseInt(strings[9]);
            int speedCluster = Integer.parseInt(strings[10]);
            int sizeCluster = Integer.parseInt(strings[11]);
            double latCluster = Double.parseDouble(strings[12]);
            double lngCluster = Double.parseDouble(strings[13]);

            output =
                "+ Received *TrafficService* messageID '"
                    + messageID
                    + "' from CarID:'"
                    + fromCarID
                    + "': Speed:'"
                    + vehicleSpeed
                    + "': Direction:'"
                    + directionCluster * 22.5
                    + "': Speed:'"
                    + speedCluster
                    + "': Size:'"
                    + sizeCluster
                    + "': Cluster lattitude:'"
                    + latCluster
                    + "': Cluster longitude:'"
                    + lngCluster
                    + " km/h, Lattitude:'"
                    + vehicleLattitude
                    + "' Longitude:'"
                    + vehicleLongitude
                    + "', Heading:'"
                    + heading
                    + "', HopCount = "
                    + hopCount;
            waveManager.userInterface.output(output);

            trafficService.computeData(
                directionCluster, speedCluster, sizeCluster, latCluster, lngCluster);
          } else {
            output =
                "+ Received *Control* message advertising '"
                    + messageGroup
                    + "' from CarID '"
                    + fromCarID
                    + "'";
            waveManager.userInterface.output(output);

            boolean alreadyListening = false;
            for (int i = 0; i < groupsToListenTo.length; i++) {
              if (groupsToListenTo[i][0].equals(messageGroup)) {
                output = "Group '" + messageGroup + "' is already in groupsToListenTo";
                waveManager.userInterface.output(output);
                alreadyListening = true;
              }
            }
            if (!alreadyListening) {
              numGroupsToListenTo++;
              waveManager.userInterface.updateNumberGroupsListeningTo(numGroupsToListenTo);
              groupsToListenTo[numGroupsToListenTo][0] = messageGroup;
              groupsToListenTo[numGroupsToListenTo][1] = String.valueOf(System.currentTimeMillis());

              output = "Added '" + messageGroup + "' to groupsToListenTo";
              waveManager.userInterface.output(output);
            }
          }

          // DECIDE IF CONTROL MESSAGES SHOULD BE PASSED HERE
          if (hopCount < maxHopCount) {
            if (fromGroup.equals(brakeService.serviceGroup)) {
              passAlongMessage(
                  fromCarID,
                  fromGroup,
                  messageID,
                  hopCount,
                  messageGroup,
                  heading,
                  vehicleSpeed,
                  vehicleLattitude,
                  vehicleLongitude,
                  strings[9]);
            } else {
              passAlongMessage(
                  fromCarID,
                  fromGroup,
                  messageID,
                  hopCount,
                  messageGroup,
                  heading,
                  vehicleSpeed,
                  vehicleLattitude,
                  vehicleLongitude,
                  "");
            }
          }
        }
      } else {
        numPacketsOmitted++;
        waveManager.userInterface.updateNumPacketsOmitted(numPacketsOmitted);

        output = "X Omitted own message";
        waveManager.userInterface.output(output);
      }
    } catch (Exception e) {
    }
  }
Example #17
0
 public Node(HazelcastInstanceImpl hazelcastInstance, Config config, NodeContext nodeContext) {
   this.hazelcastInstance = hazelcastInstance;
   this.threadGroup = hazelcastInstance.threadGroup;
   this.config = config;
   configClassLoader = config.getClassLoader();
   this.groupProperties = new GroupProperties(config);
   SerializationService ss;
   try {
     ss =
         new SerializationServiceBuilder()
             .setClassLoader(configClassLoader)
             .setConfig(config.getSerializationConfig())
             .setManagedContext(hazelcastInstance.managedContext)
             .setHazelcastInstance(hazelcastInstance)
             .build();
   } catch (Exception e) {
     throw ExceptionUtil.rethrow(e);
   }
   serializationService = (SerializationServiceImpl) ss;
   systemLogService = new SystemLogService(groupProperties.SYSTEM_LOG_ENABLED.getBoolean());
   final AddressPicker addressPicker = nodeContext.createAddressPicker(this);
   try {
     addressPicker.pickAddress();
   } catch (Throwable e) {
     throw ExceptionUtil.rethrow(e);
   }
   final ServerSocketChannel serverSocketChannel = addressPicker.getServerSocketChannel();
   address = addressPicker.getPublicAddress();
   localMember = new MemberImpl(address, true, UuidUtil.createMemberUuid(address));
   String loggingType = groupProperties.LOGGING_TYPE.getString();
   loggingService =
       new LoggingServiceImpl(
           systemLogService, config.getGroupConfig().getName(), loggingType, localMember);
   logger = loggingService.getLogger(Node.class.getName());
   initializer = NodeInitializerFactory.create(configClassLoader);
   try {
     initializer.beforeInitialize(this);
   } catch (Throwable e) {
     try {
       serverSocketChannel.close();
     } catch (Throwable ignored) {
     }
     throw ExceptionUtil.rethrow(e);
   }
   securityContext =
       config.getSecurityConfig().isEnabled() ? initializer.getSecurityContext() : null;
   nodeEngine = new NodeEngineImpl(this);
   clientEngine = new ClientEngineImpl(this);
   connectionManager = nodeContext.createConnectionManager(this, serverSocketChannel);
   partitionService = new PartitionServiceImpl(this);
   clusterService = new ClusterServiceImpl(this);
   textCommandService = new TextCommandServiceImpl(this);
   initializer.printNodeInfo(this);
   buildNumber = initializer.getBuildNumber();
   VersionCheck.check(this, initializer.getBuild(), initializer.getVersion());
   JoinConfig join = config.getNetworkConfig().getJoin();
   MulticastService mcService = null;
   try {
     if (join.getMulticastConfig().isEnabled()) {
       MulticastConfig multicastConfig = join.getMulticastConfig();
       MulticastSocket multicastSocket = new MulticastSocket(null);
       multicastSocket.setReuseAddress(true);
       // bind to receive interface
       multicastSocket.bind(new InetSocketAddress(multicastConfig.getMulticastPort()));
       multicastSocket.setTimeToLive(multicastConfig.getMulticastTimeToLive());
       try {
         // set the send interface
         final Address bindAddress = addressPicker.getBindAddress();
         // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4417033
         // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402758
         if (!bindAddress.getInetAddress().isLoopbackAddress()) {
           multicastSocket.setInterface(bindAddress.getInetAddress());
         }
       } catch (Exception e) {
         logger.warning(e);
       }
       multicastSocket.setReceiveBufferSize(64 * 1024);
       multicastSocket.setSendBufferSize(64 * 1024);
       String multicastGroup = System.getProperty("hazelcast.multicast.group");
       if (multicastGroup == null) {
         multicastGroup = multicastConfig.getMulticastGroup();
       }
       multicastConfig.setMulticastGroup(multicastGroup);
       multicastSocket.joinGroup(InetAddress.getByName(multicastGroup));
       multicastSocket.setSoTimeout(1000);
       mcService = new MulticastService(this, multicastSocket);
       mcService.addMulticastListener(new NodeMulticastListener(this));
     }
   } catch (Exception e) {
     logger.severe(e);
   }
   this.multicastService = mcService;
   initializeListeners(config);
   joiner = nodeContext.createJoiner(this);
 }
Example #18
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    System.out.println("已开始");
    if (!run) {
      return;
    }
    DatagramPacket received;
    String mes;
    String hisname;
    InetAddress hisip;
    String frdshow;
    byte[] hisuid;
    String hisuidString;
    try {
      broadSocket.setSoTimeout(0);
    } catch (SocketException e1) {
      // TODO Auto-generated catch block
      chat.catchexception(e1);
    }
    while (true) {
      received = new DatagramPacket(new byte[47], 47);
      try {
        broadSocket.receive(received);
        hisuid = Arrays.copyOfRange(received.getData(), 0, 8);
        StringBuilder sb = new StringBuilder();
        for (byte b : hisuid) {
          String b_temp = String.valueOf(b);
          if (b_temp.contains("-")) {
            b_temp = b_temp.replaceAll("-", "");
            sb.append("-");
          }
          for (int i = 3 - b_temp.length(); i > 0; i--) {
            sb.append("0");
          }
          sb.append(b_temp);
        }
        hisuidString = sb.toString();
        System.out.println("收到" + hisuidString);
        hisip = InetAddress.getByAddress(Arrays.copyOfRange(received.getData(), 8, 12));
        System.out.println(hisip);
        mes = new String(received.getData(), 12, received.getLength() - 12);
        System.out.println(mes);
        if (hisuidString.equals(myuidString)) {
          continue;
        }
        chat.frd_online_time.put(hisuidString, System.currentTimeMillis());
        if (mes.startsWith("find=")) {
          hisname = mes.replaceAll("find=", "");
          if (chat.frdlist.containsKey(hisuidString)) {
            rename(hisuidString, hisip, hisname);
            returnmes(hisip);
          } else {
            online(hisuidString, hisip, hisname, "online");
            returnmes(hisip);
          }
        } else if (mes.startsWith("rtrn=")) {
          hisname = mes.replaceAll("rtrn=", "");
          if (chat.frdlist.containsKey(hisuidString)) {
            rename(hisuidString, hisip, hisname);
          } else {
            online(hisuidString, hisip, hisname, "find");
          }
        } else if (mes.startsWith("renm=")) {
          hisname = mes.replaceAll("renm=", "");
          if (!chat.frdlist.containsKey(hisuidString)) {
            online(hisuidString, hisip, hisname, "find");
            returnmes(hisip);
          } else {
            rename(hisuidString, hisip, hisname);
          }
        } else if (mes.startsWith("offl=")) {

          hisip = chat.frdlist.get(hisuidString);
          hisname = chat.frdname.get(hisip);
          frdshow = hisname + "---" + hisip.getHostAddress();
          chat.friendlsit.remove(frdshow);
          chat.frdlist.remove(hisuidString);
          chat.frdname.remove(hisip);
          chat.zhuangtailan.setText(frdshow + "下线了");
        }
      } catch (SocketException e1) {
        broadSocket.close();
        break;
      } catch (IOException e) {
        if (chat.trayIcon != null) {
          chat.trayIcon.displayMessage(
              "线程出错", "广播信息接收线程出现错误,请将程序目录下的“错误日志.log”文件发给作者", TrayIcon.MessageType.ERROR);
        }
        chat.catchexception(e);
      }
    }
  }
Example #19
0
  public static void main(String args[]) throws Exception {
    DatagramSocket r_clients = null, s_clients = null;
    MulticastSocket servers = null, b_clients = null;

    local = Integer.parseInt(args[1]);
    rec = Integer.parseInt(args[0]);

    System.out.println("Recieving arp on port " + rec + "...");
    System.out.println("Recieving reply arp on port " + (rec + 1) + "...");
    System.out.println("\nEmulating gateway on port " + local + "\nWaiting...");

    try {
      r_clients = new DatagramSocket(rec);

      s_clients = new DatagramSocket(rec + 1);

      b_clients = new MulticastSocket(local);
      b_clients.joinGroup(InetAddress.getByName(group));

      servers = new MulticastSocket(serv_port);
      servers.joinGroup(InetAddress.getByName(group));

      servers.setSoTimeout(10);
      s_clients.setSoTimeout(10);
      b_clients.setSoTimeout(10);
      r_clients.setSoTimeout(10);
    } catch (Exception e) {
      System.out.println("error: " + e.toString());
      System.exit(1);
    }

    byte arp_buf[] = new byte[28];
    DatagramPacket arp_packet = new DatagramPacket(arp_buf, arp_buf.length);

    while (true) {
      try {
        servers.receive(arp_packet);
        System.out.println("\nGot arp from servers");

        System.out.println("Sending arp to local computers");
        arp_packet.setAddress(InetAddress.getByName(group));
        arp_packet.setPort(local);
        try {
          b_clients.send(arp_packet, (byte) 255);
        } catch (Exception e3) {
        }
      } catch (Exception e) {
        try {
          r_clients.receive(arp_packet);
          System.out.println("\nGot arp from client");

          System.out.println("Sending ARP");
          arp_packet.setAddress(InetAddress.getByName(group));
          arp_packet.setPort(serv_port);
          try {
            servers.send(arp_packet, (byte) 255);
          } catch (Exception e3) {
          }
        } catch (Exception e2) {
          try {
            s_clients.receive(arp_packet);
            System.out.println("\nGot reply arp from client");

            arp_packet.setAddress(InetAddress.getByName(group));
            arp_packet.setPort(2500);
            try {
              s_clients.send(arp_packet);
            } catch (Exception e3) {
            }
          } catch (Exception e4) {
          }
        }
      }
    }
  }