@Override
  public void run() {
    if (mDownloadManager != null) {
      mDownloadManager.onStartDownload(this);
    }
    mException = null;
    InputStream inputStream = null;
    BufferedWriter bufferedWriter = null;
    try {
      int bufferSize = 8192;
      if (mDownloadRateLimit > 0 && bufferSize > mDownloadRateLimit << 10) {
        bufferSize = mDownloadRateLimit << 10;
      }
      mTargetFile = new File(getTempFilePath());
      URL url = new URL(getTargetURL());
      String host = url.getHost();
      int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();

      mSocket = new Socket();
      mSocket.setReceiveBufferSize(bufferSize);
      mSocket.setSoTimeout(getTimeoutInterval());
      SocketAddress address = new InetSocketAddress(host, port);
      mSocket.connect(address, getTimeoutInterval());

      Log.i(TAG, "socket receive buffer size is: " + mSocket.getReceiveBufferSize());
      bufferedWriter =
          new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF8"));
      String requestStr = "GET " + url.getFile() + " HTTP/1.1\r\n";

      String hostHeader = "Host: " + host + "\r\n";
      String acceptHeader =
          "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
      String charsetHeader = "Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n";
      String languageHeader = "Accept-Language: zh-CN,zh;q=0.8\r\n";
      String keepHeader = "Connection: close\r\n";

      bufferedWriter.write(requestStr);
      bufferedWriter.write(hostHeader);
      bufferedWriter.write(acceptHeader);
      bufferedWriter.write(charsetHeader);
      bufferedWriter.write(languageHeader);
      bufferedWriter.write(keepHeader);
      if (mLoadedByteLength > 0) {
        bufferedWriter.write("Range: bytes=" + mLoadedByteLength + "-\r\n");
      } else {
        guessFileName();
        String folderPath = getFilePath().substring(0, getFilePath().lastIndexOf("/"));
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
          folder.mkdirs();
        } else {
          deleteFile(getFilePath());
          deleteFile(getTempFilePath());
        }
      }
      bufferedWriter.write("\r\n");
      bufferedWriter.flush();
      inputStream = mSocket.getInputStream();
      Log.i(TAG, inputStream.getClass().getName());
      HttpResponseHeaderParser responseHeader = new HttpResponseHeaderParser();
      String responseHeaderLine = null;
      char readChar = 0;
      StringBuilder headerBuilder = new StringBuilder();
      while ((byte) (readChar = (char) inputStream.read()) != -1) {
        headerBuilder.append(readChar);
        if (readChar == 10) {
          responseHeaderLine = headerBuilder.substring(0, headerBuilder.length() - 2);
          headerBuilder.setLength(0);
          if (responseHeaderLine.length() == 0) {
            break;
          } else {
            responseHeader.addResponseHeaderLine(responseHeaderLine);
            Log.i(TAG, responseHeaderLine);
          }
        }
      }
      Log.i(TAG, "status code: " + responseHeader.getStatusCode());

      if (mTotalByteLength == 0) {
        mTotalByteLength = responseHeader.getContentLength();
      }
      mOutputStream = new FileOutputStream(mTargetFile, true);
      mByteOutput = new ByteArrayOutputStream();
      byte[] buffer = new byte[bufferSize];
      int length = -1;
      mTimeStart = System.currentTimeMillis();
      mDeltaLByteLength = 0;
      mSleepTime = 0;
      while ((length = inputStream.read(buffer)) != -1 && mIsDownloading) {
        Log.i(TAG, "receive data: " + length + " available: " + inputStream.available());
        mByteOutput.write(buffer, 0, length);
        if (mByteOutput.size() >= getMemoryCacheSize() << 10) {
          writeCache();
        }
        limitTheByteRate(length);
      }
      Log.i(TAG, "receive data: " + length + " available: " + inputStream.available());

    } catch (Exception e) {
      mException = e;
    } finally {
      if (mException != null && mIsDownloading && mDownloadManager != null) {
        mDownloadManager.onFailedDownload(this);
      }
      try {
        if (bufferedWriter != null) {
          bufferedWriter.close();
          bufferedWriter = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (inputStream != null) {
          inputStream.close();
          inputStream = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      stop();
      writeCache();
      try {
        if (mOutputStream != null) {
          mOutputStream.close();
          mOutputStream = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (mByteOutput != null) {
          mByteOutput.close();
          mByteOutput = null;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #2
0
  /**
   * Configures the socket for use
   *
   * @param sock
   * @throws SocketException, IllegalArgumentException if setting the options on the socket failed.
   */
  protected void initialiseSocket(Socket sock) throws SocketException, IllegalArgumentException {
    if (socketOptions != null) {
      IntrospectionSupport.setProperties(socket, socketOptions);
    }

    try {
      sock.setReceiveBufferSize(socketBufferSize);
      sock.setSendBufferSize(socketBufferSize);
    } catch (SocketException se) {
      LOG.warn("Cannot set socket buffer size = " + socketBufferSize);
      LOG.debug("Cannot set socket buffer size. Reason: " + se, se);
    }
    sock.setSoTimeout(soTimeout);

    if (keepAlive != null) {
      sock.setKeepAlive(keepAlive.booleanValue());
    }

    if (soLinger > -1) {
      sock.setSoLinger(true, soLinger);
    } else if (soLinger == -1) {
      sock.setSoLinger(false, 0);
    }
    if (tcpNoDelay != null) {
      sock.setTcpNoDelay(tcpNoDelay.booleanValue());
    }
    if (!this.trafficClassSet) {
      this.trafficClassSet = setTrafficClass(sock);
    }
  }
Example #3
0
  private void setSocketParameters(Socket client_sock) throws SocketException {
    if (log.isTraceEnabled())
      log.trace(
          "["
              + local_addr
              + "] accepted connection from "
              + client_sock.getInetAddress()
              + ":"
              + client_sock.getPort());
    try {
      client_sock.setSendBufferSize(send_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting send buffer size to " + send_buf_size + " bytes", ex);
    }
    try {
      client_sock.setReceiveBufferSize(recv_buf_size);
    } catch (IllegalArgumentException ex) {
      if (log.isErrorEnabled())
        log.error("exception setting receive buffer size to " + send_buf_size + " bytes", ex);
    }

    client_sock.setKeepAlive(true);
    client_sock.setTcpNoDelay(tcp_nodelay);
    if (linger > 0) client_sock.setSoLinger(true, linger);
    else client_sock.setSoLinger(false, -1);
  }
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;
 }
  void applySocketParams(Socket s) {
    if (sendBuffer > 0) {
      try {
        s.setSendBufferSize(sendBuffer);
      } catch (SocketException e) {
        logger.error("error setting sendBuffer to " + sendBuffer, e);
      }
    }

    if (recvBuffer > 0) {
      try {
        s.setReceiveBufferSize(recvBuffer);
      } catch (SocketException e) {
        logger.error("error setting recvBuffer to " + recvBuffer, e);
      }
    }

    try {
      s.setTcpNoDelay(tcpNoDelay);
    } catch (SocketException e) {
      logger.error("error setting TcpNoDelay to " + tcpNoDelay, e);
    }

    try {
      s.setKeepAlive(keepAlive);
    } catch (SocketException e) {
      logger.error("error setting KeepAlive to " + keepAlive, e);
    }
  }
 @Override
 public void setReceiveBufferSize(int receiveBufferSize) {
   try {
     socket.setReceiveBufferSize(receiveBufferSize);
   } catch (SocketException e) {
     throw new ChannelException(e);
   }
 }
 protected void initSocket(Socket socket) throws Exception {
   if (ioService.getSocketLingerSeconds() > 0) {
     socket.setSoLinger(true, ioService.getSocketLingerSeconds());
   }
   socket.setKeepAlive(ioService.getSocketKeepAlive());
   socket.setTcpNoDelay(ioService.getSocketNoDelay());
   socket.setReceiveBufferSize(ioService.getSocketReceiveBufferSize() * KILO_BYTE);
   socket.setSendBufferSize(ioService.getSocketSendBufferSize() * KILO_BYTE);
 }
  private void acceptUpload() throws IOException {
    try {
      Socket sock = UploadGateKeeper.accept();
      sock.setReceiveBufferSize(BufferSize);
      sock.setSendBufferSize(BufferSize);
      sock.setSoTimeout(1000);
      System.out.println("client connected");
      InputStream in_stream = sock.getInputStream();
      while (in_stream.available() == 0) {
        Thread.sleep(10);
      }
      if (in_stream.available() == 23) {
        // Policy file...
        byte[] req = new byte[in_stream.available()];
        in_stream.read(req);
        String request = new String(req, "UTF-8");
        OutputStream out = sock.getOutputStream();
        out.write(CrossDomainFile.getBytes("UTF-8"));
        out.flush();
        out.close();
        sock.close();
        System.out.println("policy done");
        return;
      }
      byte[] size_buff = new byte[8];
      in_stream.read(size_buff);
      // Size...
      long size = Helper.bytesToLong(size_buff);
      System.out.println("File size: " + size);
      byte[] name_size_buff = new byte[2];
      in_stream.read(name_size_buff);
      int name_size = Helper.bytesToInt(name_size_buff);
      byte[] name_buff = new byte[name_size];
      in_stream.read(name_buff);
      // Name...
      String name = new String(name_buff, "UTF-8");
      System.out.println("File name: " + name);

      byte[] param_size_buff = new byte[2];
      in_stream.read(param_size_buff);
      int param_size = Helper.bytesToInt(param_size_buff);
      byte[] param_buff = new byte[param_size];
      in_stream.read(param_buff);
      // Params...
      String params = new String(param_buff, "UTF-8");
      System.out.println("File params: " + params);
      FileUploadProcessorItem item =
          new FileUploadProcessorItem(sock, Path, size, name, params, StartID);
      UploadItems.put(StartID, item);
      StartID++;
    } catch (SocketTimeoutException toex) {
      // System.out.println("Time out");
    } catch (Exception ex) {
      System.out.println(Helper.getStackTraceString(ex));
    }
  }
  protected SocketBox openSocket() throws Exception {

    logger.debug("server.accept()");

    Socket newSocket = myServer.accept();

    // set TCP buffer size
    if (gSession.TCPBufferSize != Session.SERVER_DEFAULT) {
      logger.debug("setting socket's TCP buffer size to " + gSession.TCPBufferSize);
      newSocket.setReceiveBufferSize(gSession.TCPBufferSize);
      newSocket.setSendBufferSize(gSession.TCPBufferSize);
    }

    logger.debug("server.accept() returned");

    if (!gSession.dataChannelAuthentication.equals(DataChannelAuthentication.NONE)) {
      logger.debug("authenticating");
      newSocket =
          GridFTPServerFacade.authenticate(
              newSocket,
              false, // this is NOT client socket
              gSession.credential,
              gSession.dataChannelProtection,
              gSession.dataChannelAuthentication);
    } else {
      // do not authenticate
      logger.debug("not authenticating");
    }

    // mark the socket as busy and store in the global socket pool

    ManagedSocketBox sBox = new ManagedSocketBox();
    sBox.setSocket(newSocket);
    sBox.setStatus(ManagedSocketBox.BUSY);

    if (session.transferMode != GridFTPSession.MODE_EBLOCK) {

      // synchronize to prevent race condidion against
      // the section in GridFTPServerFacade.setTCPBufferSize
      synchronized (sBox) {
        sBox.setReusable(false);
      }
    }

    SocketPool socketPool = ((EBlockParallelTransferContext) context).getSocketPool();
    logger.debug("adding new socket to the pool");
    socketPool.add(sBox);
    logger.debug(
        "available cached sockets: "
            + socketPool.countFree()
            + "; busy: "
            + socketPool.countBusy());

    return sBox;
  }
Example #10
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);
   }
 }
  /** {@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;
  }
 @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);
   }
 }
  /** Create a socket for the given host/port */
  public Object makeObject(Object key) throws Exception {
    SocketDestination dest = (SocketDestination) key;
    Socket socket = new Socket();
    socket.setReceiveBufferSize(this.socketBufferSize);
    socket.setSendBufferSize(this.socketBufferSize);
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(soTimeoutMs);
    socket.connect(new InetSocketAddress(dest.getHost(), dest.getPort()));

    recordSocketCreation(dest, socket);

    return new SocketAndStreams(socket);
  }
 private void maybeOpenConnection() throws IOException {
   if ((this.connection == null) || (!this.connection.isOpen())) {
     BasicHttpParams localBasicHttpParams = new BasicHttpParams();
     Socket localSocket = this.socketFactory.createSocket();
     localSocket =
         this.socketFactory.connectSocket(
             localSocket,
             this.host.getHostName(),
             this.host.getPort(),
             null,
             0,
             localBasicHttpParams);
     localSocket.setReceiveBufferSize(8192);
     this.connection.bind(localSocket, localBasicHttpParams);
   }
 }
Example #15
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 #16
0
 public void run() {
   while (!srv_sock.isClosed()) {
     Socket client_sock = null;
     DataInputStream in = null;
     try {
       client_sock = srv_sock.accept();
       client_sock.setTcpNoDelay(TCP_NODELAY);
       client_sock.setReceiveBufferSize(SOCK_RECV_BUF_SIZE);
       client_sock.setSendBufferSize(SOCK_SEND_BUF_SIZE);
       in = new DataInputStream(new BufferedInputStream(client_sock.getInputStream()));
       while (!client_sock.isClosed()) handleRequest(in);
     } catch (Exception e) {
       Util.close(client_sock);
       Util.close(in);
     }
   }
 }
 public static void main(String[] args) throws IOException {
   ServerSocket serverSocket = new ServerSocket(8000);
   Socket s = serverSocket.accept();
   /*
    * 输出缓冲区大小
    */
   s.setSendBufferSize(2048);
   /*
    * 接受缓冲区
    */
   s.setReceiveBufferSize(2048);
   /*
    * socket流等待时间超时就不接受数据
    */
   // s.setSoTimeout(5000);
   /*
    * 一个字节的紧急数据,接收方没法区别是否紧急
    */
   s.setOOBInline(true);
   /*
    * 设置网络服务类型高可靠性4表示高可靠性
    * 8表示高吞吐
    * 10表示最小延迟
    * 2表示低成本
    */
   s.setTrafficClass(0x04 | 0x10);
   // 接受客服端信息流
   InputStream in = s.getInputStream();
   // 向客户端发送流
   ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   byte[] buff = new byte[1024];
   int len = -1;
   do {
     try {
       len = in.read(buff);
       if (len != -1) {
         buffer.write(buff, 0, len);
       }
     } catch (SocketTimeoutException e) {
       System.out.println("等待读超时");
       len = 0;
     }
   } while (len != -1);
   System.out.println(new String(buffer.toByteArray()));
 }
Example #18
0
  /** @param args */
  public static void main(String[] args) {
    try {
      server = new ServerSocket(org.voltdb.client.Client.VOLTDB_SERVER_PORT);
    } catch (IOException e) {
      System.out.println("Could not listen on port");
      e.printStackTrace();
      System.exit(-1);
    }

    fs = new FastSerializer();
    byte[] buffer = new byte[1024 * 1024 * 2];
    try {
      while (true) {
        client = server.accept();
        client.setReceiveBufferSize(1024 * 1024 * 2);
        client.setSendBufferSize(1024 * 1024 * 2);

        byte[] lengthBytes = new byte[4];
        while (client.getInputStream().read(lengthBytes) > 0) {
          FastDeserializer fds = new FastDeserializer(lengthBytes);
          int length = fds.readInt();
          int count = 0;
          byte[] type = new byte[1];
          count += client.getInputStream().read(type);

          // Reads up to a full message
          while (count < length) {
            count += client.getInputStream().read(buffer, count - 1, buffer.length - count + 1);
          }
          echo(type, buffer, length);
        }

        client.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        server.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 public ClientActionRobot(String... ip) {
   String _ip = "localhost";
   if (ip.length > 0) {
     _ip = ip[0];
   }
   try {
     // 1. creating a socket to connect to the server
     requestSocket = new Socket(_ip, 2004);
     requestSocket.setReceiveBufferSize(100000);
     System.out.println("Connected to " + _ip + " in port 2004");
     out = requestSocket.getOutputStream();
     out.flush();
     in = requestSocket.getInputStream();
   } catch (UnknownHostException unknownHost) {
     System.err.println("You are trying to connect to an unknown host!");
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
 /**
  * Sets socket attributes on the socket.
  *
  * @param socket The socket.
  * @throws SocketException
  */
 protected void setSocketAttributes(Socket socket) throws SocketException {
   if (this.soTimeout >= 0) {
     socket.setSoTimeout(this.soTimeout);
   }
   if (this.soSendBufferSize > 0) {
     socket.setSendBufferSize(this.soSendBufferSize);
   }
   if (this.soReceiveBufferSize > 0) {
     socket.setReceiveBufferSize(this.soReceiveBufferSize);
   }
   socket.setTcpNoDelay(this.soTcpNoDelay);
   if (this.soLinger >= 0) {
     socket.setSoLinger(true, this.soLinger);
   }
   if (this.soTrafficClass >= 0) {
     socket.setTrafficClass(this.soTrafficClass);
   }
   socket.setKeepAlive(this.soKeepAlive);
 }
Example #21
0
  protected void setSocketParameters(Socket client_sock) throws SocketException {
    try {
      client_sock.setSendBufferSize(server.send_buf_size);
    } catch (IllegalArgumentException ex) {
      server.log.error(
          "%s: exception setting send buffer to %d bytes: %s",
          server.local_addr, server.send_buf_size, ex);
    }
    try {
      client_sock.setReceiveBufferSize(server.recv_buf_size);
    } catch (IllegalArgumentException ex) {
      server.log.error(
          "%s: exception setting receive buffer to %d bytes: %s",
          server.local_addr, server.recv_buf_size, ex);
    }

    client_sock.setKeepAlive(true);
    client_sock.setTcpNoDelay(server.tcp_nodelay);
    if (server.linger > 0) client_sock.setSoLinger(true, server.linger);
    else client_sock.setSoLinger(false, -1);
  }
Example #22
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 #23
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 #24
0
  /**
   * Establishes the TCP/IP connection to serverName and portNumber of this Connection
   *
   * @throws SQLTimeoutException If the connection cannot be established within the connect timeout
   *     (either explicitly set or implied by the OS timeout of the socket)
   * @throws SQLException If the connection cannot be established.
   */
  public final void socketConnect() throws SQLException {
    try {
      socket = new Socket();
      socket.setTcpNoDelay(true);
      final int connectTimeout = attachProperties.getConnectTimeout();
      final int socketConnectTimeout;
      if (connectTimeout != -1) {
        // connectTimeout is in seconds, need milliseconds
        socketConnectTimeout = (int) TimeUnit.SECONDS.toMillis(connectTimeout);
        // Blocking timeout initially identical to connect timeout
        socket.setSoTimeout(socketConnectTimeout);
      } else {
        // socket connect timeout is not set, so indefinite (0)
        socketConnectTimeout = 0;
        // Blocking timeout to normal socket timeout, 0 if not set
        socket.setSoTimeout(Math.max(attachProperties.getSoTimeout(), 0));
      }

      final int socketBufferSize = attachProperties.getSocketBufferSize();
      if (socketBufferSize != IConnectionProperties.DEFAULT_SOCKET_BUFFER_SIZE) {
        socket.setReceiveBufferSize(socketBufferSize);
        socket.setSendBufferSize(socketBufferSize);
      }

      socket.connect(new InetSocketAddress(getServerName(), getPortNumber()), socketConnectTimeout);
    } catch (SocketTimeoutException ste) {
      throw new FbExceptionBuilder()
          .timeoutException(ISCConstants.isc_network_error)
          .messageParameter(getServerName())
          .cause(ste)
          .toSQLException();
    } catch (IOException ioex) {
      throw new FbExceptionBuilder()
          .exception(ISCConstants.isc_network_error)
          .messageParameter(getServerName())
          .cause(ioex)
          .toSQLException();
    }
  }
Example #25
0
  public void init(String local_addr, String remote_addr, int local_port, int remote_port)
      throws Exception {
    local = new InetSocketAddress(local_addr, local_port);
    remote = new InetSocketAddress(remote_addr, remote_port);
    srv_sock =
        Util.createServerSocket(
            new DefaultSocketFactory(), "server", local.getAddress(), local.getPort());
    System.out.println("Listening on " + srv_sock.getLocalSocketAddress());
    acceptor = new Acceptor();
    acceptor.start();

    sock = new Socket();
    // sock.bind(local);
    sock.setSendBufferSize(SOCK_SEND_BUF_SIZE);
    sock.setReceiveBufferSize(SOCK_RECV_BUF_SIZE);
    try {
      sock.connect(remote);
      output = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
      System.out.println("Connected to " + sock.getRemoteSocketAddress());
    } catch (Throwable t) {
      System.out.println("Failed connecting to " + remote + ": will only act as server");
    }
  }
 @Override
 public void run() {
   final CountDownLatch cdl = new CountDownLatch(2);
   final SocketReader rdr = new SocketReader(sock, cdl);
   final SocketWriter wtr = new SocketWriter(sock, cdl);
   try {
     sock.setSendBufferSize(0xFFFF);
     sock.setReceiveBufferSize(0xFFFF);
     sock.setTcpNoDelay(true);
     System.out.println("Connection begin: " + sock);
     // Read
     threadPool.submit(rdr);
     // Write
     threadPool.submit(wtr);
     // Wait end
     cdl.await();
   } catch (Exception e) {
     e.printStackTrace(System.out);
   } finally {
     System.out.println("Connection end: " + sock);
     close();
   }
 }
 @Override
 public void setReceiveBufferSize(int size) throws SocketException {
   sock.setReceiveBufferSize(size);
 }
  @Override
  public void run() {
    try {
      while (active) {
        try {
          // listen for and accept a client connection to serverSocket
          final Socket socket = serverSocket.accept();

          if (server.getDistributedManager() != null) {
            final ODistributedServerManager.NODE_STATUS nodeStatus =
                server.getDistributedManager().getNodeStatus();
            if (nodeStatus != ODistributedServerManager.NODE_STATUS.ONLINE) {
              OLogManager.instance()
                  .warn(
                      this,
                      "Distributed server is not yet ONLINE (status=%s), reject incoming connection from %s. If you are trying to shutdown the server, please kill the process",
                      nodeStatus,
                      socket.getRemoteSocketAddress());
              socket.close();

              // PAUSE CURRENT THREAD TO SLOW DOWN ANY POSSIBLE ATTACK
              Thread.sleep(100);
              continue;
            }
          }

          final int max = OGlobalConfiguration.NETWORK_MAX_CONCURRENT_SESSIONS.getValueAsInteger();

          int conns = server.getClientConnectionManager().getTotal();
          if (conns >= max) {
            server.getClientConnectionManager().cleanExpiredConnections();
            conns = server.getClientConnectionManager().getTotal();
            if (conns >= max) {
              // MAXIMUM OF CONNECTIONS EXCEEDED
              OLogManager.instance()
                  .warn(
                      this,
                      "Reached maximum number of concurrent connections (max=%d, current=%d), reject incoming connection from %s",
                      max,
                      conns,
                      socket.getRemoteSocketAddress());
              socket.close();

              // PAUSE CURRENT THREAD TO SLOW DOWN ANY POSSIBLE ATTACK
              Thread.sleep(100);
              continue;
            }
          }

          socket.setPerformancePreferences(0, 2, 1);
          socket.setSendBufferSize(socketBufferSize);
          socket.setReceiveBufferSize(socketBufferSize);

          // CREATE A NEW PROTOCOL INSTANCE
          ONetworkProtocol protocol = protocolType.newInstance();

          // CONFIGURE THE PROTOCOL FOR THE INCOMING CONNECTION
          protocol.config(this, server, socket, configuration);

        } catch (Throwable e) {
          if (active) OLogManager.instance().error(this, "Error on client connection", e);
        } finally {
        }
      }
    } finally {
      try {
        if (serverSocket != null && !serverSocket.isClosed()) serverSocket.close();
      } catch (IOException ioe) {
      }
    }
  }
Example #29
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);
      }
    }
  }
Example #30
0
 public void setReceiveBufferSize(int size) throws SocketException {
   mSocket.setReceiveBufferSize(size);
 }