示例#1
0
  @Override
  public void upload(UploadRequest uploadRequest) {
    ServerInfo serverInfo = uploadRequest.getServerInfo();
    String host = serverInfo.getHost();

    if (uploadRequest.isUseProxy()) {
      initializeProxy(host);
    }
    int attemptCount = 0;
    while (true) {
      try {

        login(serverInfo.getHost(), serverInfo.getLogin(), serverInfo.getPassword());

        try {
          ftpClient.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
        } catch (SocketException e) {
          LOGGER.error("socket exception: {} {}", e.getMessage(), e.getStackTrace());

          throw new RuntimeException("socket exception: " + e.getMessage());
        }

        String prefixDirectory = serverInfo.getPrefix();
        if (prefixDirectory != null) {
          ftpClient.changeWorkingDirectory(prefixDirectory);
        }

        File directory = new File(uploadRequest.getUploadDir());
        uploadDir(directory);

        ftpClient.logout();
        break;

      } catch (IOException e) {
        LOGGER.error("i/o error: {}, retrying", e.getMessage());

        attemptCount++;

        if (attemptCount > 5) {
          LOGGER.debug("choosing another proxy after 5 attempts");
          initializeProxy(host);

          attemptCount = 0;
        }
      } finally {
        if (ftpClient.isConnected()) {
          try {
            ftpClient.disconnect();
          } catch (IOException ioe) {
            // do nothing
          }
        }
      }
    }
  }
示例#2
0
 public static void main(String[] args) throws Exception {
   startServer();
   try {
     doClientSide();
   } catch (SocketException e) {
     if (!e.getMessage().equalsIgnoreCase("Socket closed")) {
       throw new Exception("Received a wrong exception message: " + e.getMessage());
     }
     System.out.println("PASSED: received the right exception message: " + e.getMessage());
   }
   if (serverException != null) {
     throw serverException;
   }
 }
 /** Sends the next speakable to Avatar. */
 private void sendNextSpeakable() {
   final QueuedSpeakable next = speakables.peek();
   final SpeakableText speakable = next.getSpeakable();
   final String utterance;
   final SsmlDocument document;
   if (speakable instanceof SpeakableSsmlText) {
     final SpeakableSsmlText ssml = (SpeakableSsmlText) speakable;
     document = ssml.getDocument();
     final Speak speak = document.getSpeak();
     utterance = speak.getTextContent();
   } else {
     utterance = speakable.getSpeakableText();
     document = null;
   }
   ErrorEvent error = null;
   try {
     final String bml = createBML(utterance, document);
     sendToAvatar(bml);
   } catch (SocketException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (UnknownHostException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (IOException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (XMLStreamException e) {
     error = new BadFetchError(e.getMessage(), e);
   }
   if (error != null) {
     synchronized (listeners) {
       for (SynthesizedOutputListener listener : listeners) {
         listener.outputError(error);
       }
     }
   }
 }
示例#4
0
  // Print IP addresses and network interfaces
  private static void printIPAddresses() {
    try {
      InetAddress localhost = InetAddress.getLocalHost();
      System.out.println("Server: IP Address: " + localhost.getHostAddress());
      // Just in case this host has multiple IP addresses....
      InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
      if (allMyIps != null && allMyIps.length > 1) {
        System.out.println("Server: Full list of IP addresses:");
        for (InetAddress allMyIp : allMyIps) {
          System.out.println("    " + allMyIp);
        }
      }
    } catch (UnknownHostException ex) {
      System.out.println("Server: Cannot get IP address of local host");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }

    try {
      System.out.println("Server: Full list of network interfaces:");
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        System.out.println("    " + intf.getName() + " " + intf.getDisplayName());
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {
          System.out.println("        " + enumIpAddr.nextElement().toString());
        }
      }
    } catch (SocketException ex) {
      System.out.println("Server: Cannot retrieve network interface list");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }
  }
  private void serviceClient(Socket clientSocket) {
    IHttpRequest request;
    IHttpResponse response;

    // pour éviter un blocage dans le serveur
    try {
      clientSocket.setSoTimeout(10000);
    } catch (SocketException e) {
      logger.error(e.getMessage());
      try {
        clientSocket.close();
      } catch (IOException e1) {
        logger.error(e1.getMessage());
      }
      return;
    }

    HttpClient httpClient = new HttpClient(clientSocket);

    try {
      request = httpClient.getHttpRequest();
      logger.info("receive :\n" + request);
      response = process.run(request);
    } catch (IOException | MethodeTypeException e) {
      logger.error(e.getMessage());
      response = DefaultResponseFactory.createResponseBadRequestException(e);
    }

    httpClient.sendHttpResponse(response);
    httpClient.shutdown();
  }
示例#6
0
 public SocketServer() {
   try {
     initializeSoftPWM();
     System.out.println("Waiting for connect ...");
     createSocket();
     System.out.println("Device is connected");
     createDoorBell();
     createCommandReader();
     // Wait until user stops the application
     Scanner scanIn = new Scanner(System.in);
     String nextLine = "";
     while (true) {
       nextLine = scanIn.nextLine();
       if (nextLine.equals("!exit")) {
         System.exit(0);
       }
       ;
     }
   } catch (SocketException e) {
     System.out.println(String.format("Socket connect is broken: \n %s", e.getMessage()));
     System.exit(0);
   } catch (IOException e) {
     System.out.println(String.format("Something wrong: \n %s", e.getMessage()));
     System.exit(0);
   }
 }
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket();
     String stringMsg = "0";
     String prevReply = "0";
     InetAddress aHost =
         InetAddress.getByName("localhost"); // recieve a message from the same computer
     int serverPort = 6789; // agreed port
     while (true) {
       stringMsg = "" + (Integer.parseInt(stringMsg) + 1);
       byte[] message = stringMsg.getBytes();
       DatagramPacket request = new DatagramPacket(message, message.length, aHost, serverPort);
       System.out.printf("Producer: Sending: %s\n", stringMsg);
       aSocket.send(request); // send a message
       byte[] buffer = new byte[1000];
       DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(reply); // wait for a reply
       try {
         Thread.sleep(2000); // have a small waiting period
       } catch (InterruptedException e) {
       }
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) aSocket.close();
   }
 }
示例#8
0
      @Override
      protected CommandResult innerExecute(ArgoClientContext context) {

        if (!_niNames.isEmpty()) {
          for (String niName : _niNames) {
            NetworkInterface ni = null;
            try {
              ni = NetworkInterface.getByName(niName);
            } catch (SocketException e) {
              Console.error(
                  "SocketException when attempting to get Network Interface named ["
                      + niName
                      + "]");
              Console.error(e.getMessage());
            }
            if (ni == null) {
              Console.error("Network Interface named [" + niName + "] does not exist.");
            } else {
              if (!context.getNIList().contains(niName)) {
                context.getNIList().add(niName);
                Console.info("Added Network Interface named [" + niName + "]");
              } else {
                Console.info("Already using Network Interface named [" + niName + "]");
              }
            }
          }
        }

        return CommandResult.OK;
      }
  /** Initializes the query system by binding it to a port */
  private boolean initQuerySystem() {
    try {
      querySocket = new DatagramSocket(queryPort, InetAddress.getByName(serverHostname));
      registerSocket(querySocket);
      querySocket.setSoTimeout(500);
      return true;
    } catch (SocketException var2) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Socket): "
              + var2.getMessage());
    } catch (UnknownHostException var3) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Unknown Host): "
              + var3.getMessage());
    } catch (Exception var4) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (E): "
              + var4.getMessage());
    }

    return false;
  }
  /** {@inheritDoc} */
  @Override
  public void open() {
    logger.debug("open(): Opening TCP Connection");

    try {
      tcpSocket = new Socket();
      SocketAddress TPIsocketAddress = new InetSocketAddress(ipAddress, tcpPort);
      tcpSocket.connect(TPIsocketAddress, connectTimeout);

      setInput(tcpSocket.getInputStream());
      setOutput(tcpSocket.getOutputStream());

      setReaderThread(new PowerMaxReaderThread(getInput(), this));
      getReaderThread().start();

      setConnected(true);
    } catch (UnknownHostException exception) {
      logger.debug("open(): Unknown Host Exception: {}", exception.getMessage());
      setConnected(false);
    } catch (SocketException socketException) {
      logger.debug("open(): Socket Exception: {}", socketException.getMessage());
      setConnected(false);
    } catch (IOException ioException) {
      logger.debug("open(): IO Exception: {}", ioException.getMessage());
      setConnected(false);
    } catch (Exception exception) {
      logger.debug("open(): Exception: {}", exception.getMessage());
      setConnected(false);
    }
  }
示例#11
0
  private boolean g() {
    try {
      this.socket = new DatagramSocket(this.bindPort, InetAddress.getByName(this.motd));
      this.a(this.socket);
      this.socket.setSoTimeout(500);
      return true;
    } catch (SocketException socketexception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (Socket): "
              + socketexception.getMessage());
    } catch (UnknownHostException unknownhostexception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (Unknown Host): "
              + unknownhostexception.getMessage());
    } catch (Exception exception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (E): "
              + exception.getMessage());
    }

    return false;
  }
示例#12
0
  /**
   * @param theUrl
   * @param conAttempts
   * @return
   * @throws IOException
   */
  public int getResposeCode(String theUrl, int conAttempts)
      throws IOException { // throws IOException
    URL newUrl = new URL(theUrl);
    // These codes are returned to indicate either fault or not.
    int ERROR_CODE = 1000, OK_CODE = 0;

    HttpURLConnection huc = (HttpURLConnection) newUrl.openConnection();
    huc.setRequestMethod("HEAD");
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setReadTimeout(2000);
    huc.connect();
    try {
      return huc.getResponseCode();

    } catch (java.net.SocketException e) {
      if (e.getMessage().equalsIgnoreCase("Unexpected end of file from server"))
        return OK_CODE; // link still valid so return a small positive int that isn't a http status
                        // code
      else
        return ERROR_CODE; // error, return a large int that isn't included in any http status code

    } catch (java.net.SocketTimeoutException e) {
      if (e.getMessage().equalsIgnoreCase("Read timed out")) {
        if (conAttempts != MAX_CONNECTION_ATTEMPTS) return getResposeCode(theUrl, conAttempts + 1);
        else
          return ERROR_CODE; // ERROR return a large int that isn't included in any http status code
      } else return ERROR_CODE;

    } catch (IOException e) {
      e.printStackTrace();
      return ERROR_CODE; // error, return a large int that isn't included in any http status code
    }
  }
示例#13
0
  @Override
  protected void launchNewThread() throws IOException {
    final Socket socket;
    try {
      socket = server.accept();
    } catch (SocketException e) {
      if (e.getMessage().equals("socket closed")) {
        return;
      }
      throw e;
    }
    try {
      JLSTConnection client = new JLSTConnection(socket);
      client.writeUnencryptedObject(crypto.getPublicKey());

      DataPackage data = (DataPackage) client.readUnencryptedObject();

      SecretKey key = new SecretKeySpec(crypto.decrypt((byte[]) data.getObjects()[0]), "AES");
      client.getAESSecurityService().setPublicKey(key);
      client.getAESSecurityService().setPrivateKey(key);

      client
          .getAESSecurityService()
          .setParameters(new IvParameterSpec(crypto.decrypt((byte[]) data.getObjects()[1])));

      ClientData event = new ClientData(client);
      launchThreadForConnectedClient(event, "JLSTServer");
    } catch (CryptographyException | ClassNotFoundException e) {
      launchNewThread();
      throw new IOException(e);
    }
  }
 /** Start the thread. Exits when the client has been completely handled. */
 @Override
 public void run() {
   try {
     GELFClientHandlerIF client = null;
     if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
       LOG.info("Received message is chunked. Handling now.");
       client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
     } else {
       LOG.info("Received message is not chunked. Handling now.");
       client = new SimpleGELFClientHandler(this.receivedGelfSentence);
     }
     client.handle();
   } catch (InvalidGELFTypeException e) {
     LOG.error("Invalid GELF type in message: " + e.getMessage(), e);
   } catch (InvalidGELFHeaderException e) {
     LOG.error("Invalid GELF header in message: " + e.getMessage(), e);
   } catch (InvalidGELFCompressionMethodException e) {
     LOG.error("Invalid compression method of GELF message: " + e.getMessage(), e);
   } catch (java.util.zip.DataFormatException e) {
     LOG.error("Invalid compression data format in GELF message: " + e.getMessage(), e);
   } catch (java.io.UnsupportedEncodingException e) {
     LOG.error("Invalid enconding of GELF message: " + e.getMessage(), e);
   } catch (java.io.EOFException e) {
     LOG.error("EOF Exception while handling GELF message: " + e.getMessage(), e);
   } catch (java.net.SocketException e) {
     LOG.error("SocketException while handling GELF message: " + e.getMessage(), e);
   } catch (java.io.IOException e) {
     LOG.error("IO Error while handling GELF message: " + e.getMessage(), e);
   } catch (Exception e) {
     LOG.error("Exception caught while handling GELF message: " + e.getMessage(), e);
   }
 }
示例#15
0
文件: Connection.java 项目: m1kc/msim
  @Override
  public void run() {
    try {
      if (!streamsReady) openStreams();
      while (true) {
        Packet p = new Packet(account, dis);
        parent.processPacket(this, p);
      }
    } catch (SocketTimeoutException ex) {
      Log.print(uid + " (" + account + ") отключился по таймауту.");
    } catch (SocketException ex) {
      if (ex.getMessage().hashCode() == "Connection reset".hashCode()) {
        Log.print(uid + " (" + account + ") отключился.");
      } else {
        Log.error("Страшная хуйня на соединении " + uid + " (" + account + ").", ex);
      }
    } catch (EOFException ex) {
      Log.print(uid + " (" + account + ") отключился.");
    } catch (IOException ex) {
      Log.error("Страшная хуйня на соединении " + uid + " (" + account + ").", ex);
    } finally {
      parent.connections.remove(this);

      try {
        parent.accountDisonnected(account);
      } catch (IOException ex) {
        // Да похуй уже.
      }
    }
  }
示例#16
0
 /**
  * 获取本机网卡配置IP地址
  *
  * @return IP地址
  */
 public String getLocalHost() {
   String host = "";
   try {
     // 根据网卡取本机配置的IP
     Enumeration<?> en = NetworkInterface.getNetworkInterfaces();
     while (en.hasMoreElements()) {
       NetworkInterface i = (NetworkInterface) en.nextElement();
       for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements(); ) {
         InetAddress addr = (InetAddress) en2.nextElement();
         if (!addr.isLoopbackAddress()) {
           if (addr instanceof Inet4Address) {
             // 返回
             return addr.getHostAddress();
           }
         }
       }
     }
     // Windows 采用以下方法
     if ("".equals(host)) {
       host = InetAddress.getLocalHost().getHostAddress();
     }
   } catch (SocketException e) {
     logger.error("get the IP of the NIC configuration fails.{}", e.getMessage());
   } catch (Exception e) {
     //
   }
   return host;
 }
示例#17
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
  /**
   * The main RESTful GET method; the other one ({@link #make_restful_get(String, String, int)})
   * calls this one with a pre-populated logging parameter.
   *
   * @param baseUrl A {@link String} URL to request from.
   * @param tag A {@link String} tag for logging/analytics purposes.
   * @param timeout An {@link Integer} value containing the number of milliseconds to wait before
   *     considering a server request to have timed out.
   * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for
   *     this request or not.
   * @return A {@link ServerResponse} object containing the result of the RESTful request.
   */
  private ServerResponse make_restful_get(
      String baseUrl, String tag, int timeout, int retryNumber, boolean log) {
    String modifiedUrl = baseUrl;
    JSONObject getParameters = new JSONObject();
    HttpsURLConnection connection = null;
    if (timeout <= 0) {
      timeout = DEFAULT_TIMEOUT;
    }
    if (addCommonParams(getParameters, retryNumber)) {
      modifiedUrl += this.convertJSONtoString(getParameters);
    } else {
      return new ServerResponse(tag, NO_BRANCH_KEY_STATUS);
    }

    try {
      if (log) PrefHelper.Debug("BranchSDK", "getting " + modifiedUrl);
      URL urlObject = new URL(modifiedUrl);
      connection = (HttpsURLConnection) urlObject.openConnection();
      connection.setConnectTimeout(timeout);
      connection.setReadTimeout(timeout);

      if (connection.getResponseCode() >= 500 && retryNumber < prefHelper_.getRetryCount()) {
        try {
          Thread.sleep(prefHelper_.getRetryInterval());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        retryNumber++;
        return make_restful_get(baseUrl, tag, timeout, retryNumber, log);
      } else {
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
            && connection.getErrorStream() != null) {
          return processEntityForJSON(
              connection.getErrorStream(), connection.getResponseCode(), tag, log, null);
        } else {
          return processEntityForJSON(
              connection.getInputStream(), connection.getResponseCode(), tag, log, null);
        }
      }
    } catch (SocketException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (UnknownHostException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
      return new ServerResponse(tag, 500);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
 private DHCPSocket openSocket(DHCPSocket s) {
   try {
     s = new DHCPSocket(68);
   } catch (SocketException se) {
     if (s != null) s.close();
     lastError = se.getMessage();
     return null;
   }
   return s;
 }
示例#20
0
 // 绑定本地端口
 public boolean ConnectSocket() {
   try {
     if (recvSocket == null) recvSocket = new DatagramSocket(localDataPort);
     if (rPacket == null) rPacket = new DatagramPacket(rBuffer, rBuffer.length);
     return true;
   } catch (SocketException se) {
     DisConnectSocket();
     log("open udp port error:" + se.getMessage());
     return false;
   }
 }
示例#21
0
  @JRubyMethod(name = "initialize", required = 1, optional = 1, visibility = Visibility.PRIVATE)
  public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    IRubyObject _host = args[0];
    IRubyObject _port = args.length > 1 ? args[1] : context.nil;

    String host;
    if (_host.isNil() || ((_host instanceof RubyString) && ((RubyString) _host).isEmpty())) {
      host = "0.0.0.0";
    } else if (_host instanceof RubyFixnum) {
      // numeric host, use it for port
      _port = _host;
      host = "0.0.0.0";
    } else {
      host = _host.convertToString().toString();
    }

    int port = SocketUtils.getPortFrom(context, _port);

    try {
      InetAddress addr = InetAddress.getByName(host);

      ssc = ServerSocketChannel.open();
      socket_address = new InetSocketAddress(addr, port);

      ssc.socket().bind(socket_address);

      initSocket(runtime, new ChannelDescriptor(ssc, newModeFlags(runtime, ModeFlags.RDWR)));

    } catch (UnknownHostException e) {
      throw SocketUtils.sockerr(runtime, "initialize: name or service not known");

    } catch (BindException e) {
      throw runtime.newErrnoEADDRFromBindException(e);

    } catch (SocketException e) {
      String msg = e.getMessage();

      if (msg.indexOf("Permission denied") != -1) {
        throw runtime.newErrnoEACCESError("bind(2)");
      } else {
        throw SocketUtils.sockerr(runtime, "initialize: name or service not known");
      }

    } catch (IOException e) {
      throw SocketUtils.sockerr(runtime, "initialize: name or service not known");

    } catch (IllegalArgumentException iae) {
      throw SocketUtils.sockerr(runtime, iae.getMessage());
    }

    return this;
  }
    /** @review runSafe OK */
    @Override
    public void run() {
      log.debug(prefix() + "ReceiverThread started.");
      try {
        while (!isInterrupted()) {
          /*
           * TODO: if we implement network view it should return a
           * ProgressMonitor with Util#getRunnableContext(), that we
           * can use here.
           */
          progress = SubMonitor.convert(new NullProgressMonitor());
          progress.beginTask("receive", 100);

          try {
            IncomingTransferObject transferObject =
                channel.receiveIncomingTransferObject(progress.newChild(1));

            listener.addIncomingTransferObject(transferObject);

          } catch (LocalCancellationException e) {
            log.info("Connection was closed by me. ");
            if (progress != null && !progress.isCanceled()) progress.setCanceled(true);
            close();
            return;
          } catch (SocketException e) {
            log.debug(prefix() + "Connection was closed by me. " + e.getMessage());
            close();
            return;
          } catch (EOFException e) {
            e.printStackTrace();

            log.debug(prefix() + "Connection was closed by peer. " + e.getMessage());
            close();
            return;
          } catch (IOException e) {
            log.error(prefix() + "Network IO Exception: " + e.getMessage(), e);

            if (e.getMessage().contains("Socket already disposed")) return;

            close();
            return;
          } catch (ClassNotFoundException e) {
            log.error(prefix() + "Received unexpected object in ReceiveThread", e);
            continue;
          }
        }
      } catch (RuntimeException e) {
        log.error(prefix() + "Internal Error in Receive Thread: ", e);
        // If there is programming problem, close the socket
        close();
      }
    }
 public StatsdAgentBackendImpl() {
   try {
     socket = new DatagramSocket();
   } catch (SocketException e) {
     log.error(e.getMessage(), e);
   }
   try {
     hostName = InetAddress.getLocalHost().getHostName();
   } catch (UnknownHostException e) {
     // This is ok it just means host specific metrics will not be published
     log.error("Unable to get local hostname", e);
   }
 }
示例#24
0
      @Override
      protected CommandResult innerExecute(ArgoClientContext context) {

        List<String> niNames;
        try {
          niNames = context.getAvailableNetworkInterfaces(_mcEnabled);
        } catch (SocketException e1) {
          Console.error("Issues getting the available network interfaces.");
          Console.error(e1.getMessage());
          return CommandResult.ERROR;
        }

        if (_mcEnabled) {
          Console.info("Available Multicast enabled Network Interfaces");
        } else {
          Console.info("All Available Network Interfaces");
        }

        for (String niName : niNames) {
          try {
            NetworkInterface ni = NetworkInterface.getByName(niName);
            StringBuffer buf = new StringBuffer();
            buf.append("NI named " + ni.getName());
            if (context.getNIList().contains(ni.getName())) {
              buf.append(" (USING) ");
            }
            buf.append(" at addresses " + ni.getInterfaceAddresses());
            Console.info(buf.toString());
          } catch (SocketException e) {
            Console.error("Issues getting the network interface for name [" + niName + "]");
            Console.error(e.getMessage());
          }
        }

        return CommandResult.OK;
      }
 public void run() {
   while ((serverSocket != null) && !serverSocket.isClosed()) {
     if (!isConnected()) {
       try {
         setupNextClient();
       } catch (SocketException xcp) {
         if (!xcp.getMessage().equals("socket closed")) {
           xcp.printStackTrace();
         }
       } catch (IOException xcp) {
         xcp.printStackTrace();
       }
     }
   }
   printIfDebug(".ServerThread: ServerAccept Thread has Stopped.");
 }
示例#26
0
  public static String getLocalAddress() {
    try {
      // 遍历网卡,查找一个非回路ip地址并返回
      Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
      ArrayList<String> ipv4Result = new ArrayList<String>();
      ArrayList<String> ipv6Result = new ArrayList<String>();
      while (enumeration.hasMoreElements()) {
        final NetworkInterface networkInterface = enumeration.nextElement();
        final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
        while (en.hasMoreElements()) {
          final InetAddress address = en.nextElement();
          if (!address.isLoopbackAddress()) {
            if (address instanceof Inet6Address) {
              ipv6Result.add(normalizeHostAddress(address));
            } else {
              ipv4Result.add(normalizeHostAddress(address));
            }
          }
        }
      }

      // 优先使用ipv4
      if (!ipv4Result.isEmpty()) {
        for (String ip : ipv4Result) {
          if (ip.startsWith("127.0") || ip.startsWith("192.168")) {
            continue;
          }

          return ip;
        }

        // 取最后一个
        return ipv4Result.get(ipv4Result.size() - 1);
      }
      // 然后使用ipv6
      else if (!ipv6Result.isEmpty()) {
        return ipv6Result.get(0);
      }
      // 然后使用本地ip
      final InetAddress localHost = InetAddress.getLocalHost();
      return normalizeHostAddress(localHost);
    } catch (SocketException e) {
      throw new IllegalStateException(e.getMessage(), e);
    } catch (UnknownHostException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
  }
示例#27
0
  /**
   * init the Selector
   *
   * @param ctx
   * @throws java.io.IOException
   */
  private final void initSelector(Context ctx) throws IOException {
    try {
      isShutDown.set(false);

      connectorInstanceHandler =
          new ConnectorInstanceHandler.ConcurrentQueueDelegateCIH(
              getConnectorInstanceHandlerDelegate());

      // Create the socket listener
      selector = Utils.openSelector();

      if (role != Role.CLIENT) {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocket = serverSocketChannel.socket();
        if (receiveBufferSize > 0) {
          try {
            serverSocket.setReceiveBufferSize(receiveBufferSize);
          } catch (SocketException se) {
            if (logger.isLoggable(Level.FINE))
              logger.log(Level.FINE, "setReceiveBufferSize exception ", se);
          } catch (IllegalArgumentException iae) {
            if (logger.isLoggable(Level.FINE))
              logger.log(Level.FINE, "setReceiveBufferSize exception ", iae);
          }
        }

        if (inet == null) {
          portRange.bind(serverSocket, ssBackLog);
        } else {
          portRange.bind(serverSocket, inet, ssBackLog);
        }

        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        serverSocket.setSoTimeout(serverTimeout);

        // Ephemeral support
        port = serverSocket.getLocalPort();
        inet = serverSocket.getInetAddress();
      }
      ctx.getController().notifyReady();
    } catch (SocketException ex) {
      throw new BindException(ex.getMessage() + ": " + port + "=" + this);
    }
  }
  /**
   * Initializes and binds a socket that on a random port number. The method would try to bind on a
   * random port and retry 5 times until a free port is found.
   *
   * @return the socket that we have initialized on a randomport number.
   */
  private DatagramSocket initRandomPortSocket() {
    DatagramSocket resultSocket = null;
    String bindRetriesStr =
        NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME);

    int bindRetries = 5;

    if (bindRetriesStr != null) {
      try {
        bindRetries = Integer.parseInt(bindRetriesStr);
      } catch (NumberFormatException ex) {
        logger.error(
            bindRetriesStr
                + " does not appear to be an integer. "
                + "Defaulting port bind retries to "
                + bindRetries,
            ex);
      }
    }

    int currentlyTriedPort = NetworkUtils.getRandomPortNumber();

    // we'll first try to bind to a random port. if this fails we'll try
    // again (bindRetries times in all) until we find a free local port.
    for (int i = 0; i < bindRetries; i++) {
      try {
        resultSocket = new DatagramSocket(currentlyTriedPort);
        // we succeeded - break so that we don't try to bind again
        break;
      } catch (SocketException exc) {
        if (exc.getMessage().indexOf("Address already in use") == -1) {
          logger.fatal(
              "An exception occurred while trying to create" + "a local host discovery socket.",
              exc);
          resultSocket = null;
          return null;
        }
        // port seems to be taken. try another one.
        logger.debug("Port " + currentlyTriedPort + " seems in use.");
        currentlyTriedPort = NetworkUtils.getRandomPortNumber();
        logger.debug("Retrying bind on port " + currentlyTriedPort);
      }
    }

    return resultSocket;
  }
  /**
   * The main RESTful GET method; the other one ({@link #make_restful_get(String, String, int)})
   * calls this one with a pre-populated logging parameter.
   *
   * @param baseUrl A {@link String} URL to request from.
   * @param tag A {@link String} tag for logging/analytics purposes.
   * @param timeout An {@link Integer} value containing the number of milliseconds to wait before
   *     considering a server request to have timed out.
   * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for
   *     this request or not.
   * @return A {@link ServerResponse} object containing the result of the RESTful request.
   */
  private ServerResponse make_restful_get(
      String baseUrl, String tag, int timeout, int retryNumber, boolean log) {
    String modifiedUrl = baseUrl;
    JSONObject getParameters = new JSONObject();
    if (addCommonParams(getParameters, retryNumber)) {
      modifiedUrl += this.convertJSONtoString(getParameters);
    } else {
      return new ServerResponse(tag, NO_BRANCH_KEY_STATUS);
    }

    try {
      if (log) PrefHelper.Debug("BranchSDK", "getting " + modifiedUrl);
      HttpGet request = new HttpGet(modifiedUrl);
      HttpResponse response = getGenericHttpClient(timeout).execute(request);
      if (response.getStatusLine().getStatusCode() >= 500
          && retryNumber < prefHelper_.getRetryCount()) {
        try {
          Thread.sleep(prefHelper_.getRetryInterval());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        retryNumber++;
        return make_restful_get(baseUrl, tag, timeout, retryNumber, log);
      } else {
        return processEntityForJSON(
            response.getEntity(), response.getStatusLine().getStatusCode(), tag, log, null);
      }

    } catch (ClientProtocolException ex) {
      if (log)
        PrefHelper.Debug(
            getClass().getSimpleName(), "Client protocol exception: " + ex.getMessage());
    } catch (SocketException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (UnknownHostException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
      return new ServerResponse(tag, 500);
    }
    return null;
  }
示例#30
0
 /** Starts media application */
 public boolean startApp() {
   printLog("starting JMF " + media_type);
   try {
     int_socket = new UdpSocket(JmfMMReceiver.pickFreePort());
     ext_socket = new UdpSocket(local_port);
     if (dir == FlowSpec.SEND_ONLY || dir == FlowSpec.FULL_DUPLEX)
       sender =
           new JmfMMSender(
               media_type, media_format, int_socket, ext_socket, remote_soaddr, media_source);
     if (dir == FlowSpec.RECV_ONLY || dir == FlowSpec.FULL_DUPLEX)
       receiver = new JmfMMReceiver(media_type, ext_socket, int_socket);
   } catch (java.net.SocketException e) {
     printLog(e.getMessage());
     e.printStackTrace();
     return false;
   }
   return true;
 }