Example #1
0
  void SocketTests() throws Exception {
    Socket s1 = new Socket();

    test("Socket should be created with SO_REUSEADDR disabled");
    check(!s1.getReuseAddress());

    test("Socket.setReuseAddress(true)");
    s1.setReuseAddress(true);
    check(s1.getReuseAddress());

    test("Socket.setReuseAddress(false)");
    s1.setReuseAddress(false);
    check(!s1.getReuseAddress());

    /* bind to any port */
    s1.bind(new InetSocketAddress(0));

    test("Binding Socket to port already in use should throw " + "a BindException");
    Socket s2 = new Socket();
    try {
      s2.bind(new InetSocketAddress(s1.getLocalPort()));
      failed();
    } catch (BindException e) {
      passed();
    }
    s2.close();

    s1.close();
  }
Example #2
0
  private static void connectAndPlay(VideoComponent vc, String settings, String addr)
      throws UnknownHostException, IOException {
    // find this ip
    updateResource();

    Socket skt = null;
    if (addr.length() > 0) {
      Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
      while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements()) {
          InetAddress i = (InetAddress) ee.nextElement();
          if (!i.isLinkLocalAddress() && !i.isLoopbackAddress()) {
            pushLog("CLNT START IP:" + i.getHostAddress());
            clientLoc = i.getHostAddress();
          }
        }
      }
      serverLoc = addr;
      skt = new Socket(serverLoc, 45000);
    } else if (addr.length() == 0) {
      clientLoc = "127.0.0.1";
      serverLoc = "127.0.0.1";
      skt = new Socket("localhost", 45000);
    }

    skt.setReuseAddress(true);
    BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
    out = new PrintWriter(skt.getOutputStream(), true);

    JSONObject portNeg = new JSONObject(in.readLine());
    int port = portNeg.getInt("port");
    System.out.println("Client port: " + port);

    JSONObject json_settings = new JSONObject();
    json_settings.put("settings", attribute + " " + clientbw + " " + request);
    out.println(json_settings.toString());

    pushLog("> SYS: CNCT SUCCESS");
    startStreaming(vc, settings, port);

    pushLog("> CTRL: LISTENING FOR COMMANDS");
    Scanner s = new Scanner(System.in);
    String line;
    JSONObject json_command;
    while (true) {
      line = s.nextLine();
      json_command = new JSONObject();
      json_command.put("command", line);
      // json_command.put("bandwidth", "");
      out.println(json_command.toString());

      if (line.equals("stop")) break;
    }

    in.close();
    out.close();
    skt.close();
  }
Example #3
0
 public TCPConnection(int Id, InetAddress address, int port, InetAddress localAddr, int localPort)
     throws ConnectException, IOException, BindException {
   socketId = Id;
   socket = new Socket(address, port, localAddr, localPort);
   socket.setReuseAddress(true);
   type = Connection.Type.DSL;
 }
Example #4
0
 protected SelectableChannel getSelectableChannel(
     SocketAddress remoteAddress, SocketAddress localAddress) throws IOException {
   SocketChannel newSocketChannel = SocketChannel.open();
   Socket newSocket = newSocketChannel.socket();
   if (receiveBufferSize > 0) {
     try {
       newSocket.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 (sendBufferSize > 0) {
     try {
       newSocket.setSendBufferSize(sendBufferSize);
     } catch (SocketException se) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", se);
     } catch (IllegalArgumentException iae) {
       if (logger.isLoggable(Level.FINE))
         logger.log(Level.FINE, "setSendBufferSize exception ", iae);
     }
   }
   newSocket.setReuseAddress(reuseAddress);
   if (localAddress != null) newSocket.bind(localAddress);
   newSocketChannel.configureBlocking(false);
   return newSocketChannel;
 }
 @Override
 public void setReuseAddress(boolean reuseAddress) {
   try {
     socket.setReuseAddress(reuseAddress);
   } catch (SocketException e) {
     throw new ChannelException(e);
   }
 }
Example #6
0
 public void initSocket() {
   socket = new Socket();
   try {
     socket.setSendBufferSize(Config.SOCKET_MAX_SEND_BUFFER_SIZE);
     socket.setReceiveBufferSize(Config.SOCKET_MAX_RECEIVE_BUFFER_SIZE);
     socket.setKeepAlive(Config.SOCKET_KEEP_ALIVE_ENABLED);
     socket.setTcpNoDelay(Config.SOCKET_TCP_NO_DELAY);
     socket.setReuseAddress(true);
   } catch (SocketException e) {
     Logger.printException(this, e);
   }
 }
Example #7
0
  public Object makeObject(Object key) throws Exception {
    UMOImmutableEndpoint ep = (UMOImmutableEndpoint) key;
    int port = ep.getEndpointURI().getPort();
    InetAddress inetAddress = InetAddress.getByName(ep.getEndpointURI().getHost());
    Socket socket = createSocket(port, inetAddress);
    socket.setReuseAddress(true);

    TcpConnector connector = (TcpConnector) ep.getConnector();
    connector.configureSocket(TcpConnector.CLIENT, socket);

    return socket;
  }
 @Override
 public ClientConnection call() throws Exception {
   if (!live) {
     throw new HazelcastException("ConnectionManager is not active!!!");
   }
   SocketChannel socketChannel = null;
   try {
     socketChannel = SocketChannel.open();
     Socket socket = socketChannel.socket();
     socket.setKeepAlive(socketOptions.isKeepAlive());
     socket.setTcpNoDelay(socketOptions.isTcpNoDelay());
     socket.setReuseAddress(socketOptions.isReuseAddress());
     if (socketOptions.getLingerSeconds() > 0) {
       socket.setSoLinger(true, socketOptions.getLingerSeconds());
     }
     int bufferSize = socketOptions.getBufferSize() * KILO_BYTE;
     if (bufferSize < 0) {
       bufferSize = DEFAULT_BUFFER_SIZE_BYTE;
     }
     socket.setSendBufferSize(bufferSize);
     socket.setReceiveBufferSize(bufferSize);
     socketChannel.socket().connect(address.getInetSocketAddress(), connectionTimeout);
     SocketChannelWrapper socketChannelWrapper =
         socketChannelWrapperFactory.wrapSocketChannel(socketChannel, true);
     final ClientConnection clientConnection =
         new ClientConnection(
             ClientConnectionManagerImpl.this,
             inSelector,
             outSelector,
             connectionIdGen.incrementAndGet(),
             socketChannelWrapper,
             executionService,
             invocationService,
             client.getSerializationService());
     socketChannel.configureBlocking(true);
     if (socketInterceptor != null) {
       socketInterceptor.onConnect(socket);
     }
     authenticator.auth(clientConnection);
     socketChannel.configureBlocking(isBlock);
     socket.setSoTimeout(0);
     if (!isBlock) {
       clientConnection.getReadHandler().register();
     }
     return clientConnection;
   } catch (Exception e) {
     if (socketChannel != null) {
       socketChannel.close();
     }
     throw ExceptionUtil.rethrow(e);
   }
 }
  /** {@inheritDoc} */
  @Override
  public AsyncSocketChannelImpl setOption(SocketOption name, Object value) throws IOException {
    if (!(name instanceof StandardSocketOption)) {
      throw new IllegalArgumentException("Unsupported option " + name);
    }

    if (value == null || !name.type().isAssignableFrom(value.getClass())) {
      throw new IllegalArgumentException("Bad parameter for " + name);
    }

    StandardSocketOption stdOpt = (StandardSocketOption) name;
    final Socket socket = channel.socket();

    try {
      switch (stdOpt) {
        case SO_TIMEOUT:
          // Timeout is not supported by SocketChannel, so we need to
          // implement it outside.
          socketTimeout = ((Integer) value).intValue();
          break;

        case SO_SNDBUF:
          socket.setSendBufferSize(((Integer) value).intValue());
          break;

        case SO_RCVBUF:
          socket.setReceiveBufferSize(((Integer) value).intValue());
          break;

        case SO_KEEPALIVE:
          socket.setKeepAlive(((Boolean) value).booleanValue());
          break;

        case SO_REUSEADDR:
          socket.setReuseAddress(((Boolean) value).booleanValue());
          break;

        case TCP_NODELAY:
          socket.setTcpNoDelay(((Boolean) value).booleanValue());
          break;

        default:
          throw new IllegalArgumentException("Unsupported option " + name);
      }
    } catch (SocketException e) {
      if (socket.isClosed()) {
        throw Util.initCause(new ClosedChannelException(), e);
      }
      throw e;
    }
    return this;
  }
Example #10
0
  /**
   * Applies the current settings to the given socket.
   *
   * @param s Socket to apply the settings to
   * @return Socket the input socket
   */
  protected Socket applySettings(Socket s) {
    try {
      s.setKeepAlive(SO_KEEPALIVE);
      s.setOOBInline(OOBINLINE);
      s.setReuseAddress(SO_REUSEADDR);
      s.setTcpNoDelay(TCP_NODELAY);
      s.setOOBInline(OOBINLINE);

      s.setReceiveBufferSize(SO_RCVBUF);
      s.setSendBufferSize(SO_SNDBUF);
      s.setSoTimeout(SO_TIMEOUT);
      s.setSoLinger(SO_LINGER, LINGER);
    } catch (SocketException e) {
      throw new RuntimeException(e);
    }
    return s;
  }
Example #11
0
  private void initSocket(InetAddress address, int port, boolean nonDefaultSocket)
      throws SocketException, IOException {
    socket = new Socket();
    if (nonDefaultSocket) {
      socket.setReuseAddress(true);
      try {
        this.socket.setTcpNoDelay(true);
      } catch (SocketException e) {
        EclTcpClientPlugin.log(
            new Status(
                IStatus.ERROR,
                EclTcpClientPlugin.PLUGIN_ID,
                "Error setting TCP_NODELAY on client socket"));
      }
    }
    socket.connect(new InetSocketAddress(address, port));

    initSessionId(socket);
  }
Example #12
0
  public NetworkConnection(String host, int port, ByteReceiver receiver) {
    _socket = new Socket();
    try {
      _socket.setReuseAddress(true);
      _socket.setTcpNoDelay(true);
      _socket.setSendBufferSize(_bufferSize);
      _socket.setReceiveBufferSize(_bufferSize);

      InetAddress address = InetAddress.getByName(host);
      _socket.connect(new InetSocketAddress(address, port), 60 * 1000);
      _out = Channels.newChannel(_socket.getOutputStream());
    } catch (UnknownHostException e) {
      throw new RuntimeException("Error connecting to given host", e);
    } catch (IOException e) {
      throw new RuntimeException("IO error when connecting to peer", e);
    }

    _receiver = receiver;
    _receiverThread = new Thread(this);
    _receiverThread.start();
  }
Example #13
0
 /** open real socket and set time out when waitForAck is enabled is socket open return directly */
 protected void openSocket() throws IOException {
   if (isConnected()) return;
   try {
     socket = new Socket();
     InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
     socket.connect(sockaddr, (int) getTimeout());
     socket.setSendBufferSize(getTxBufSize());
     socket.setReceiveBufferSize(getRxBufSize());
     socket.setSoTimeout((int) getTimeout());
     socket.setTcpNoDelay(getTcpNoDelay());
     socket.setKeepAlive(getSoKeepAlive());
     socket.setReuseAddress(getSoReuseAddress());
     socket.setOOBInline(getOoBInline());
     socket.setSoLinger(getSoLingerOn(), getSoLingerTime());
     socket.setTrafficClass(getSoTrafficClass());
     setConnected(true);
     soOut = socket.getOutputStream();
     soIn = socket.getInputStream();
     setRequestCount(0);
     setConnectTime(System.currentTimeMillis());
     if (log.isDebugEnabled())
       log.debug(
           sm.getString(
               "IDataSender.openSocket",
               getAddress().getHostAddress(),
               new Integer(getPort()),
               new Long(0)));
   } catch (IOException ex1) {
     SenderState.getSenderState(getDestination()).setSuspect();
     if (log.isDebugEnabled())
       log.debug(
           sm.getString(
               "IDataSender.openSocket.failure",
               getAddress().getHostAddress(),
               new Integer(getPort()),
               new Long(0)),
           ex1);
     throw (ex1);
   }
 }
Example #14
0
  public void connect() {
    if (!isConnected()) {
      try {
        socket = new Socket();
        // ->@wjw_add
        socket.setReuseAddress(true);
        socket.setKeepAlive(true); // Will monitor the TCP connection is valid
        socket.setTcpNoDelay(
            true); // Socket buffer Whetherclosed, to ensure timely delivery of data
        socket.setSoLinger(
            true, 0); // Control calls close () method, the underlying socket is closed immediately
        // <-@wjw_add

        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        outputStream = new RedisOutputStream(socket.getOutputStream());
        inputStream = new RedisInputStream(socket.getInputStream());
      } catch (IOException ex) {
        throw new JedisConnectionException(ex);
      }
    }
  }
 @Override
 public void setReuseAddress(boolean on) throws SocketException {
   sock.setReuseAddress(on);
 }
  public synchronized BlockingRowSet openReaderSocket(final BaseStep baseStep)
      throws IOException, KettleException {
    this.baseStep = baseStep;

    final BlockingRowSet rowSet = new BlockingRowSet(baseStep.getTransMeta().getSizeRowset());

    // Make sure we handle the case with multiple step copies running on a
    // slave...
    //
    rowSet.setThreadNameFromToCopy(sourceStep, sourceStepCopyNr, targetStep, targetStepCopyNr);
    rowSet.setRemoteSlaveServerName(targetSlaveServerName);

    final int portNumber = Integer.parseInt(baseStep.environmentSubstitute(port));
    final String realHostname = baseStep.environmentSubstitute(hostname);

    // Connect to the server socket (started during BaseStep.init())
    // Because the accept() call on the server socket can be called after we
    // reached this code
    // it is best to build in a retry loop with a time-out here.
    //
    long startTime = System.currentTimeMillis();
    boolean connected = false;
    KettleException lastException = null;

    // // timeout with retry until connected
    while (!connected
        && (TIMEOUT_IN_SECONDS > (System.currentTimeMillis() - startTime) / 1000)
        && !baseStep.isStopped()) {
      try {
        socket = new Socket();
        socket.setReuseAddress(true);

        baseStep.logDetailed(
            "Step variable MASTER_HOST : [" + baseStep.getVariable("MASTER_HOST") + "]");
        baseStep.logDetailed(
            "Opening client (reader) socket to server ["
                + Const.NVL(realHostname, "")
                + ":"
                + port
                + "]");
        socket.connect(new InetSocketAddress(realHostname, portNumber), 5000);

        connected = true;

        if (compressingStreams) {
          gzipInputStream = new GZIPInputStream(socket.getInputStream());
          bufferedInputStream = new BufferedInputStream(gzipInputStream, bufferSize);
        } else {
          bufferedInputStream = new BufferedInputStream(socket.getInputStream(), bufferSize);
        }
        inputStream = new DataInputStream(bufferedInputStream);

        lastException = null;
      } catch (Exception e) {
        lastException =
            new KettleException(
                "Unable to open socket to server " + realHostname + " port " + portNumber, e);
      }
      if (lastException != null) {
        // Sleep for a while
        try {
          Thread.sleep(250);
        } catch (InterruptedException e) {
          if (socket != null) {
            socket.shutdownInput();
            socket.shutdownOutput();
            socket.close();
            baseStep.logDetailed(
                "Closed connection to server socket to read rows from remote step on server "
                    + realHostname
                    + " port "
                    + portNumber
                    + " - Local port="
                    + socket.getLocalPort());
          }

          throw new KettleException(
              "Interrupted while trying to connect to server socket: " + e.toString());
        }
      }
    }

    // See if all was OK...
    if (lastException != null) {

      baseStep.logError("Error initialising step: " + lastException.toString());
      if (socket != null) {
        socket.shutdownInput();
        socket.shutdownOutput();
        socket.close();
        baseStep.logDetailed(
            "Closed connection to server socket to read rows from remote step on server "
                + realHostname
                + " port "
                + portNumber
                + " - Local port="
                + socket.getLocalPort());
      }
      throw lastException;
    } else {
      if (inputStream == null)
        throw new KettleException(
            "Unable to connect to the SocketWriter in the "
                + TIMEOUT_IN_SECONDS
                + "s timeout period.");
    }

    baseStep.logDetailed(
        "Opened connection to server socket to read rows from remote step on server "
            + realHostname
            + " port "
            + portNumber
            + " - Local port="
            + socket.getLocalPort());

    // Create a thread to take care of the reading from the client socket.
    // The rows read will be put in a RowSet buffer.
    // That buffer will hand over the rows to the step that has this RemoteStep
    // object defined
    // as a remote input step.
    //
    Runnable runnable =
        new Runnable() {
          public void run() {
            try {

              // First read the row meta data from the socket...
              //
              RowMetaInterface rowMeta = null;
              while (!baseStep.isStopped() && rowMeta == null) {
                try {
                  rowMeta = new RowMeta(inputStream);
                } catch (SocketTimeoutException e) {
                  rowMeta = null;
                }
              }

              if (rowMeta == null) {
                throw new KettleEOFException(); // leave now.
              }

              // And a first row of data...
              //
              Object[] rowData = getRowOfData(rowMeta);

              // Now get the data itself, row by row...
              //
              while (rowData != null && !baseStep.isStopped()) {
                baseStep.incrementLinesInput();
                baseStep.decrementLinesRead();

                if (baseStep.log.isDebug())
                  baseStep.logDebug("Received row from remote step: " + rowMeta.getString(rowData));

                baseStep.putRowTo(rowMeta, rowData, rowSet);
                baseStep.decrementLinesWritten();
                rowData = getRowOfData(rowMeta);
              }
            } catch (KettleEOFException e) {
              // Nothing, we're simply done reading...
              //
              if (baseStep.log.isDebug())
                baseStep.logDebug(
                    "Finished reading from remote step on server "
                        + hostname
                        + " port "
                        + portNumber);

            } catch (Exception e) {
              baseStep.logError("Error reading from client socket to remote step", e);
              baseStep.setErrors(1);
              baseStep.stopAll();
            } finally {
              // Close the input socket
              if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) {
                try {
                  socket.shutdownInput();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error shutting down input channel on client socket connection to remote step",
                      e);
                }
              }
              if (socket != null && !socket.isClosed() && !socket.isOutputShutdown()) {
                try {
                  socket.shutdownOutput();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error shutting down output channel on client socket connection to remote step",
                      e);
                }
              }
              if (socket != null && !socket.isClosed()) {
                try {
                  socket.close();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error shutting down client socket connection to remote step", e);
                }
              }
              if (inputStream != null) {
                try {
                  inputStream.close();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error closing input stream on socket connection to remote step", e);
                }
                inputStream = null;
              }
              if (bufferedInputStream != null) {
                try {
                  bufferedInputStream.close();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error closing input stream on socket connection to remote step", e);
                }
              }
              bufferedInputStream = null;
              if (gzipInputStream != null) {
                try {
                  gzipInputStream.close();
                } catch (Exception e) {
                  baseStep.logError(
                      "Error closing input stream on socket connection to remote step", e);
                }
              }
              gzipInputStream = null;
              baseStep.logDetailed(
                  "Closed connection to server socket to read rows from remote step on server "
                      + realHostname
                      + " port "
                      + portNumber
                      + " - Local port="
                      + socket.getLocalPort());
            }

            // signal baseStep that nothing else comes from this step.
            //
            rowSet.setDone();
          }
        };
    new Thread(runnable).start();

    return rowSet;
  }
Example #17
0
  /** {@inheritDoc} */
  public void configureChannel(SelectableChannel channel) throws IOException {
    Socket socket = ((SocketChannel) channel).socket();

    channel.configureBlocking(false);

    if (!channel.isOpen()) {
      return;
    }

    try {
      if (socketTimeout >= 0) {
        socket.setSoTimeout(socketTimeout);
      }
    } catch (SocketException ex) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "setSoTimeout exception ", ex);
      }
    }

    try {
      if (linger >= 0) {
        socket.setSoLinger(true, linger);
      }
    } catch (SocketException ex) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "setSoLinger exception ", ex);
      }
    }

    try {
      socket.setKeepAlive(isKeepAlive);
    } catch (SocketException ex) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "setKeepAlive exception ", ex);
      }
    }

    try {
      socket.setTcpNoDelay(tcpNoDelay);
    } catch (SocketException ex) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "setTcpNoDelay exception ", ex);
      }
    }

    if (receiveBufferSize > 0) {
      try {
        socket.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 (sendBufferSize > 0) {
      try {
        socket.setSendBufferSize(sendBufferSize);
      } catch (SocketException se) {
        if (logger.isLoggable(Level.FINE))
          logger.log(Level.FINE, "setSendBufferSize exception ", se);
      } catch (IllegalArgumentException iae) {
        if (logger.isLoggable(Level.FINE))
          logger.log(Level.FINE, "setSendBufferSize exception ", iae);
      }
    }

    try {
      socket.setReuseAddress(reuseAddress);
    } catch (SocketException ex) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "setReuseAddress exception ", ex);
      }
    }
  }