コード例 #1
0
  private String receiveDataUdp(InetSocketAddress clientAddress) throws IOException, JSONException {
    EmployeeList employees = new EmployeeList();
    DatagramSocket datagramServer = new DatagramSocket(clientAddress);
    byte dataFromServer[] = new byte[2048];
    boolean isTimeExpired = false;
    datagramServer.setSoTimeout((int) SECONDS.toMillis(PROTOCOL_GROUP_TIMEOUT - 5));

    System.out.println(
        "[INFO] -----------------------------------------\n"
            + "[INFO] Collecting information from nodes....");
    while (!isTimeExpired) {
      DatagramPacket datagramPacketacket =
          new DatagramPacket(dataFromServer, dataFromServer.length);
      try {
        datagramServer.receive(datagramPacketacket);
      } catch (SocketTimeoutException e) {
        System.out.println(
            "[WARNING] -----------------------------------------\n"
                + "[WARNING] Waiting time expired...");
        isTimeExpired = true;
        continue;
      }
      String receivedJson = (String) deserialize(datagramPacketacket.getData());
      System.out.println("[INFO] " + "Received employee in JSON: " + receivedJson);
      employees.add(jsonToEmployee(receivedJson));
    }
    datagramServer.close();
    return employeeToXml(employees);
  }
コード例 #2
0
 private void sendDataTcp(int dataServerPort, String xmlEmployees) throws IOException {
   ServerSocket serverSocket = new ServerSocket(dataServerPort);
   serverSocket.setSoTimeout((int) SECONDS.toMillis(100));
   boolean isTimeExpired = false;
   while (!isTimeExpired) {
     try {
       Socket socket = serverSocket.accept(); // Blocking call!
       serialize(xmlEmployees, socket.getOutputStream());
       socket.close();
     } catch (SocketTimeoutException e) {
       System.out.println(
           "[WARNING] ----------------------------------------- \n"
               + "[WARNING] Waiting time expired... Socket is closed.");
       isTimeExpired = true;
       continue;
     }
   }
   serverSocket.close();
 }