Ejemplo n.º 1
2
 private final void socketrun() {
   do {
     if (link.socketport != 0) {
       try {
         Socket socket =
             new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport);
         socket.setSoTimeout(30000);
         socket.setTcpNoDelay(true);
         link.s = socket;
       } catch (Exception _ex) {
         link.s = null;
       }
       link.socketport = 0;
     }
     if (link.runme != null) {
       Thread thread = new Thread(link.runme);
       thread.setDaemon(true);
       thread.start();
       link.runme = null;
     }
     if (link.iplookup != null) {
       String s = "unknown";
       try {
         s = InetAddress.getByName(link.iplookup).getHostName();
       } catch (Exception _ex) {
       }
       link.host = s;
       link.iplookup = null;
     }
     try {
       Thread.sleep(100L);
     } catch (Exception _ex) {
     }
   } while (true);
 }
Ejemplo n.º 2
1
  void execute(final Socket sock)
      throws IOException, ServiceNotEnabledException, ServiceNotAuthorizedException {
    rawIn = new BufferedInputStream(sock.getInputStream());
    rawOut = new SafeBufferedOutputStream(sock.getOutputStream());

    if (0 < daemon.getTimeout()) {
      sock.setSoTimeout(daemon.getTimeout() * 1000);
    }
    String cmd = new PacketLineIn(rawIn).readStringRaw();
    final int nul = cmd.indexOf('\0');
    if (nul >= 0) {
      // Newer clients hide a "host" header behind this byte.
      // Currently we don't use it for anything, so we ignore
      // this portion of the command.
      //
      cmd = cmd.substring(0, nul);
    }

    final DaemonService srv = getDaemon().matchService(cmd);
    if (srv == null) {
      return;
    }
    sock.setSoTimeout(0);
    srv.execute(this, cmd);
  }
Ejemplo n.º 3
1
  /**
   * Returns true if the connection is functional. This uses a shameful hack to peek a byte from the
   * socket.
   */
  boolean isStale() throws IOException {
    if (!isEligibleForRecycling()) {
      return true;
    }

    InputStream in = getInputStream();
    if (in.available() > 0) {
      return false;
    }

    Socket socket = getSocket();
    int soTimeout = socket.getSoTimeout();
    try {
      socket.setSoTimeout(1);
      in.mark(1);
      int byteRead = in.read();
      if (byteRead != -1) {
        in.reset();
        return false;
      }
      return true; // the socket is reporting all data read; it's stale
    } catch (SocketTimeoutException e) {
      return false; // the connection is not stale; hooray
    } catch (IOException e) {
      return true; // the connection is stale, the read or soTimeout failed.
    } finally {
      socket.setSoTimeout(soTimeout);
    }
  }
Ejemplo n.º 4
0
 /**
  * Establish a connection with the Leader found by findLeader. Retries 5 times before giving up.
  *
  * @param addr - the address of the Leader to connect to.
  * @throws IOException - if the socket connection fails on the 5th attempt
  * @throws ConnectException
  * @throws InterruptedException
  */
 protected void connectToLeader(InetSocketAddress addr)
     throws IOException, ConnectException, InterruptedException {
   sock = new Socket();
   sock.setSoTimeout(self.tickTime * self.initLimit);
   for (int tries = 0; tries < 5; tries++) {
     try {
       sock.connect(addr, self.tickTime * self.syncLimit);
       sock.setTcpNoDelay(nodelay);
       break;
     } catch (IOException e) {
       if (tries == 4) {
         LOG.error("Unexpected exception", e);
         throw e;
       } else {
         LOG.warn("Unexpected exception, tries=" + tries + ", connecting to " + addr, e);
         sock = new Socket();
         sock.setSoTimeout(self.tickTime * self.initLimit);
       }
     }
     Thread.sleep(1000);
   }
   leaderIs = M2mBinaryInputArchive.getArchive(new BufferedInputStream(sock.getInputStream()));
   bufferedOutput = new BufferedOutputStream(sock.getOutputStream());
   leaderOs = M2mBinaryOutputArchive.getArchive(bufferedOutput);
 }
Ejemplo n.º 5
0
 /**
  * Returns true if we are confident that we can read data from this connection. This is more
  * expensive and more accurate than {@link #isAlive()}; callers should check {@link #isAlive()}
  * first.
  */
 public boolean isReadable() {
   if (!(in instanceof BufferedInputStream)) {
     return true; // Optimistic.
   }
   if (isSpdy()) {
     return true; // Optimistic. We can't test SPDY because its streams are in use.
   }
   BufferedInputStream bufferedInputStream = (BufferedInputStream) in;
   try {
     int readTimeout = socket.getSoTimeout();
     try {
       socket.setSoTimeout(1);
       bufferedInputStream.mark(1);
       if (bufferedInputStream.read() == -1) {
         return false; // Stream is exhausted; socket is closed.
       }
       bufferedInputStream.reset();
       return true;
     } finally {
       socket.setSoTimeout(readTimeout);
     }
   } catch (SocketTimeoutException ignored) {
     return true; // Read timed out; socket is good.
   } catch (IOException e) {
     return false; // Couldn't read; socket is closed.
   }
 }
Ejemplo n.º 6
0
 private void dispatchEvents(LoggerContext lc) {
   try {
     socket.setSoTimeout(acceptConnectionTimeout);
     ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
     socket.setSoTimeout(0);
     addInfo(receiverId + "connection established");
     while (true) {
       ILoggingEvent event = (ILoggingEvent) ois.readObject();
       Logger remoteLogger = lc.getLogger(event.getLoggerName());
       if (remoteLogger.isEnabledFor(event.getLevel())) {
         remoteLogger.callAppenders(event);
       }
     }
   } catch (EOFException ex) {
     addInfo(receiverId + "end-of-stream detected");
   } catch (IOException ex) {
     addInfo(receiverId + "connection failed: " + ex);
   } catch (ClassNotFoundException ex) {
     addInfo(receiverId + "unknown event class: " + ex);
   } finally {
     CloseUtil.closeQuietly(socket);
     socket = null;
     addInfo(receiverId + "connection closed");
   }
 }
  /** Handshake with the debuggee */
  void handshake(Socket s, long timeout) throws IOException {
    s.setSoTimeout((int) timeout);

    byte[] hello = "JDWP-Handshake".getBytes("UTF-8");
    s.getOutputStream().write(hello);

    byte[] b = new byte[hello.length];
    int received = 0;
    while (received < hello.length) {
      int n;
      try {
        n = s.getInputStream().read(b, received, hello.length - received);
      } catch (SocketTimeoutException x) {
        throw new IOException("handshake timeout");
      }
      if (n < 0) {
        s.close();
        throw new IOException("handshake failed - connection prematurally closed");
      }
      received += n;
    }
    for (int i = 0; i < hello.length; i++) {
      if (b[i] != hello[i]) {
        throw new IOException("handshake failed - unrecognized message from target VM");
      }
    }

    // disable read timeout
    s.setSoTimeout(0);
  }
Ejemplo n.º 8
0
  /**
   * Handle a Magnet request via a socket (for TCP handling). Deiconify the application, fire MAGNET
   * request and return true as a sign that LimeWire is running.
   */
  public void fireControlThread(Socket socket, boolean magnet) {
    LOG.trace("enter fireControl");

    Thread.currentThread().setName("IncomingControlThread");
    try {
      // Only allow control from localhost
      if (!NetworkUtils.isLocalHost(socket)) {
        if (LOG.isWarnEnabled())
          LOG.warn("Invalid control request from: " + socket.getInetAddress().getHostAddress());
        return;
      }

      // First read extra parameter
      socket.setSoTimeout(Constants.TIMEOUT);
      ByteReader br = new ByteReader(socket.getInputStream());
      // read the first line. if null, throw an exception
      String line = br.readLine();
      socket.setSoTimeout(0);

      BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
      String s = CommonUtils.getUserName() + "\r\n";
      // system internal, so use system encoding
      byte[] bytes = s.getBytes();
      out.write(bytes);
      out.flush();
      if (magnet) handleMagnetRequest(line);
      else handleTorrentRequest(line);
    } catch (IOException e) {
      LOG.warn("Exception while responding to control request", e);
    } finally {
      IOUtils.close(socket);
    }
  }
Ejemplo n.º 9
0
  byte[] listenForFirstMessage() throws IOException {

    socket.setSoTimeout(0);

    if (is.read() != 0x00) {
      throw new IOException(
          "Message does not start with 0x00 as expected in by the wrapper header.");
    }

    socket.setSoTimeout(messageFragmentTimeout);

    byte version = is.readByte();

    if (version != 1) {
      throw new IOException("Version in wrapper header is not 1 but: " + version);
    }

    logicalDeviceAddress = is.readUnsignedShort();
    clientAccessPoint = is.readUnsignedShort();

    int length = is.readUnsignedShort();

    byte[] tSdu = new byte[length];

    is.readFully(tSdu);

    return tSdu;
  }
  /**
   * Creates a ClientController object that represents a connection with the server described in the
   * arguments as the specified username.
   *
   * @param ip The IP address of the server.
   * @param port The port of the server.
   * @param userName The username this client is identifying as.
   * @param chatArea The UI component to display chat messages.
   * @param sendArea The UI component where text to send should be entered.
   * @param groupList The UI component used to display a list of groups.
   * @param userList The UI component used to display a list of users in the client's current group.
   * @throws IOException If an I/O error occurs while establishing a connection.
   * @throws IllegalArgumentException If the username is invalid.
   */
  public ClientController(
      InetAddress ip,
      int port,
      String userName,
      JTextArea chatArea,
      JTextField sendArea,
      JList<String> groupList,
      JList<String> userList)
      throws IOException, IllegalArgumentException {

    this.socket = new Socket(ip, port);
    this.inputStream = socket.getInputStream();
    ClientController.groups = new HashMap<String, ArrayList<String>>();
    this.outputStream = socket.getOutputStream();
    this.writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    ClientController.userName = userName;

    socket.setSoTimeout(5000); // Limit amount of time server can take to validate username
    if (!getUserNameConfirmation()) { // Bad username
      throw new IllegalArgumentException("Duplicate or invalid username");
    }
    socket.setSoTimeout(0);

    ClientController.groupList = groupList;
    ClientController.userList = userList;

    new Receiver(socket, chatArea).start();
  }
Ejemplo n.º 11
0
  public void run() {
    ServerSocket server = null;
    try {
      server = new ServerSocket(link.getSerPort());
      System.out.println("System Online!");
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
    try {
      Socket remoteSocket = server.accept();
      System.out.println("remoteSocket accpet!");
      Socket localSocket = server.accept();
      System.out.println("localSocket  accpet!");
      remoteSocket.setSoTimeout(0);
      localSocket.setSoTimeout(0);

      remoteSocket.setTcpNoDelay(true);
      localSocket.setTcpNoDelay(true);

      new TransferDown(remoteSocket, localSocket, "ToCZ");
      new TransferUp(remoteSocket, localSocket, "ToYonYou");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 12
0
  @Test
  public void testHalfCloseClientServer() throws Exception {
    ServerSocketChannel connector = ServerSocketChannel.open();
    connector.socket().bind(null);

    Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
    client.setSoTimeout(1000);
    client.setSoLinger(false, -1);
    Socket server = connector.accept().socket();
    server.setSoTimeout(1000);
    server.setSoLinger(false, -1);

    // Write from client to server
    client.getOutputStream().write(1);

    // Server reads
    assertEquals(1, server.getInputStream().read());

    // Write from server to client with oshut
    server.getOutputStream().write(1);
    // System.err.println("OSHUT "+server);
    server.shutdownOutput();

    // Client reads response
    assertEquals(1, client.getInputStream().read());

    try {
      // Client reads -1 and does ishut
      assertEquals(-1, client.getInputStream().read());
      assertFalse(client.isInputShutdown());
      // System.err.println("ISHUT "+client);
      client.shutdownInput();

      // Client ???
      // System.err.println("OSHUT "+client);
      client.shutdownOutput();
      // System.err.println("CLOSE "+client);
      client.close();

      // Server reads -1, does ishut and then close
      assertEquals(-1, server.getInputStream().read());
      assertFalse(server.isInputShutdown());
      // System.err.println("ISHUT "+server);

      try {
        server.shutdownInput();
      } catch (SocketException e) {
        // System.err.println(e);
      }
      // System.err.println("CLOSE "+server);
      server.close();

    } catch (Exception e) {
      System.err.println(e);
      assertTrue(OS.IS_OSX);
    }
  }
Ejemplo n.º 13
0
 @Override
 public void DoStreaming(
     Socket Connection,
     InputStream pInputStream,
     int pInputStreamSize,
     OutputStream pOutputStream,
     TOnProgressHandler OnProgressHandler,
     int StreamingTimeout,
     int IdleTimeoutCounter,
     TOnIdleHandler OnIdleHandler,
     TCanceller Canceller)
     throws Exception {
   byte[] TransferBuffer = new byte[DescriptorSize];
   short Size;
   int BytesRead, BytesRead1;
   int IdleTimeoutCount = 0;
   int _StreamingTimeout = StreamingTimeout * IdleTimeoutCounter;
   while (!Canceller.flCancel) {
     try {
       if (Connection != null) Connection.setSoTimeout(StreamingTimeout);
       BytesRead =
           TNetworkConnection.InputStream_ReadData(pInputStream, TransferBuffer, DescriptorSize);
       if (BytesRead <= 0) break; // . >
       IdleTimeoutCount = 0;
     } catch (SocketTimeoutException E) {
       IdleTimeoutCount++;
       if (IdleTimeoutCount >= IdleTimeoutCounter) {
         IdleTimeoutCount = 0;
         OnIdleHandler.DoOnIdle(Canceller);
       }
       // .
       continue; // . ^
     }
     if (BytesRead != DescriptorSize) throw new IOException("wrong data descriptor"); // . =>
     // .
     BytesRead1 = 0;
     Size = (short) (((TransferBuffer[1] & 0xFF) << 8) + (TransferBuffer[0] & 0xFF));
     if (Size > 0) {
       if (Size > TransferBuffer.length) TransferBuffer = new byte[Size];
       if (Connection != null) Connection.setSoTimeout(_StreamingTimeout);
       BytesRead1 = TNetworkConnection.InputStream_ReadData(pInputStream, TransferBuffer, Size);
       if (BytesRead1 <= 0) break; // . >
       // . parse and process
       ParseFromByteArrayAndProcess(TransferBuffer, 0, Size);
       // .
       OnProgressHandler.DoOnProgress(BytesRead1, Canceller);
     }
     // .
     if (pInputStreamSize > 0) {
       pInputStreamSize -= (BytesRead + BytesRead1);
       if (pInputStreamSize <= 0) break; // . >
     }
   }
 }
  @Test
  public void testEcho() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(60000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.accept(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // wait for read timeout
    client.setSoTimeout(500);
    long start = System.currentTimeMillis();
    try {
      client.getInputStream().read();
      Assert.fail();
    } catch (SocketTimeoutException e) {
      long duration = System.currentTimeMillis() - start;
      Assert.assertThat("timeout duration", duration, greaterThanOrEqualTo(400L));
    }

    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));

    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
      int b = client.getInputStream().read();
      Assert.assertThat("expect valid char integer", b, greaterThan(0));
      assertEquals("expect characters to be same", c, (char) b);
    }
    client.close();

    for (int i = 0; i < 10; ++i) {
      if (server.isOpen()) Thread.sleep(10);
      else break;
    }
    assertFalse(server.isOpen());
  }
Ejemplo n.º 15
0
 public void setSoTimeout(int timeout) {
   try {
     _socket.setSoTimeout(timeout);
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 16
0
  public void run() {
    logger.info("Started GSN Controller on port " + gsnControllerPort);
    while (true) {
      try {
        Socket socket = mySocket.accept();
        logger.debug("Opened connection on control socket.");
        socket.setSoTimeout(GSN_CONTROL_READ_TIMEOUT);

        // Only connections from localhost are allowed
        if (ValidityTools.isLocalhost(socket.getInetAddress().getHostAddress()) == false) {
          try {
            logger.warn(
                "Connection request from IP address >"
                    + socket.getInetAddress().getHostAddress()
                    + "< was denied.");
            socket.close();
          } catch (IOException ioe) {
            // do nothing
          }
          continue;
        }
        new StopManager().start();
      } catch (SocketTimeoutException e) {
        logger.debug("Connection timed out. Message was: " + e.getMessage());
      } catch (IOException e) {
        logger.warn("Error while accepting control connection: " + e.getMessage());
      }
    }
  }
Ejemplo n.º 17
0
  @Test
  public void testMaxIdleWithRequest10() throws Exception {
    configureServer(new HelloWorldHandler());
    Socket client = newSocket(HOST, _connector.getLocalPort());
    client.setSoTimeout(10000);

    assertFalse(client.isClosed());

    OutputStream os = client.getOutputStream();
    InputStream is = client.getInputStream();

    String content = "Wibble";
    byte[] contentB = content.getBytes("utf-8");
    os.write(
        ("GET / HTTP/1.0\r\n"
                + "host: "
                + HOST
                + ":"
                + _connector.getLocalPort()
                + "\r\n"
                + "connection: keep-alive\r\n"
                + "\r\n")
            .getBytes("utf-8"));
    os.flush();

    long start = System.currentTimeMillis();
    String in = IO.toString(is);

    Thread.sleep(300);
    assertEquals(-1, is.read());

    Assert.assertTrue(System.currentTimeMillis() - start > 200);
    Assert.assertTrue(System.currentTimeMillis() - start < 5000);
  }
Ejemplo n.º 18
0
  /**
   * Waits for a client to connect to the ident server before making an appropriate response. Note
   * that this method is started by the class constructor.
   */
  public void run() {
    try {
      Socket socket = ss.accept();
      socket.setSoTimeout(60000);

      BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

      String line = reader.readLine();
      if (line != null) {
        bot.log("*** Ident request received: " + line);
        line = line + " : USERID : UNIX : " + login;
        writer.write(line + "\r\n");
        writer.flush();
        bot.log("*** Ident reply sent: " + line);
        writer.close();
      }
    } catch (Exception e) {
      // We're not really concerned with what went wrong, are we?
    }

    try {
      ss.close();
    } catch (Exception e) {
      // Doesn't really matter...
    }

    bot.log("*** The Ident server has been shut down.");
  }
Ejemplo n.º 19
0
 private boolean _connect() {
   try {
     trace.trace("client socket is connecting to server :" + this.getPeerAddr());
     lastConnectTime = System.currentTimeMillis();
     socket = new Socket();
     InetSocketAddress ar = new InetSocketAddress(hostIp, hostPort);
     socket.setSoTimeout(timeout * 1000);
     socket.connect(ar, timeout * 1000);
     connectWaitTime = 2;
   } catch (ConnectException e) {
     log.error(
         "Can't connect to:" + hostIp + "@" + hostPort + ",reason=" + e.getLocalizedMessage());
     socket = null;
     return false;
   } catch (Exception e) {
     log.error("Can't connect to:" + hostIp + "@" + hostPort);
     if (null != socket) {
       try {
         socket.close();
       } catch (Exception e1) {
       }
     }
     socket = null;
     return false;
   }
   log.info("client socket connect to server successfully:" + this.getPeerAddr());
   return true;
 }
Ejemplo n.º 20
0
 SocketConnection(Socket socket, int buffersize) throws IOException {
   this.socket = socket;
   socket.setSoTimeout(30000);
   socket.setTcpNoDelay(true);
   inputstreamWorker = new InputstreamWorker(socket.getInputStream(), buffersize);
   outputstreamWorker = new OutputstreamWorker(socket.getOutputStream(), buffersize);
 }
Ejemplo n.º 21
0
  public void testRCM() {
    try {
      Socket s = new Socket("127.0.0.1", port);
      OutputStream os = s.getOutputStream();
      s.setSoTimeout(10000);

      os.write("GET /index.html HTTP/1.0\n".getBytes());
      os.write("\n".getBytes());

      InputStream is = s.getInputStream();
      BufferedReader bis = new BufferedReader(new InputStreamReader(is));
      String line = null;

      int index;
      while ((line = bis.readLine()) != null) {
        if (line.startsWith("RCMTest")) {
          assertTrue(true);
          return;
        }
      }
    } catch (Throwable ex) {
      com.sun.grizzly.util.Utils.dumpOut("Unable to connect to: " + port);
      ex.printStackTrace();
    }
    fail("Wrong header response");
  }
Ejemplo n.º 22
0
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
Ejemplo n.º 23
0
  @Test
  public void testFileTransfer() {
    Thread th =
        new Thread() {
          public void run() {
            try {
              Socket socket = new ServerSocket(5280).accept();

              new RequestThread(socket, new XMLDatabase("profiles.xml")).run();
            } catch (IOException e) {
              fail("Server threw IO exception: " + e);
            }
          }
        };
    th.start();

    Socket client = null;
    try {
      client = new Socket("localhost", server.getPort());
      client.setSoTimeout(5000);

      PrintStream out = new PrintStream(client.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

      final String buffer = XMLDatabase.getFileContents();
      final String checksum = Utility.checksum(buffer);

      File f = new File("profiles.xml");
      if (!f.exists()) {
        fail("Requires profiles.xml to execute.");
      }

      out.println("GETFILE");
      out.println(buffer.length());
      out.println(checksum);

      String reply = in.readLine();
      if (!reply.equalsIgnoreCase("OK")) {
        fail("Server denied GETFILE request.");
      }

      Utility.sendData(client, buffer);

      reply = in.readLine();
      if (!reply.equalsIgnoreCase("OK")) {
        fail("File transfer failed. Reply: " + reply);
      }
    } catch (IOException e) {
      fail("Client threw IO exception: " + e);
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      fail("File transfer requires SHA algorithm. Exception: " + e);
    } finally {
      try {
        client.close();
        th.interrupt();
      } catch (Exception e) {
      }
    }
  }
  @Test
  public void testMaxIdleWithRequest10() throws Exception {
    configureServer(new HelloWorldHandler());

    Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
    client.setSoTimeout(10000);

    assertFalse(client.isClosed());

    OutputStream os = client.getOutputStream();
    InputStream is = client.getInputStream();

    os.write(
        ("GET / HTTP/1.0\r\n"
                + "host: "
                + _serverURI.getHost()
                + ":"
                + _serverURI.getPort()
                + "\r\n"
                + "connection: keep-alive\r\n"
                + "\r\n")
            .getBytes("utf-8"));
    os.flush();

    long start = System.currentTimeMillis();
    IO.toString(is);

    Thread.sleep(sleepTime);
    assertEquals(-1, is.read());

    Assert.assertTrue(System.currentTimeMillis() - start > minimumTestRuntime);
    Assert.assertTrue(System.currentTimeMillis() - start < maximumTestRuntime);
  }
Ejemplo n.º 25
0
 private byte getUserInput() {
   byte userInput = 0;
   while (sock == null) {
     try {
       sock = servSock.accept();
       sock.setSoTimeout(5);
       in = sock.getInputStream();
       System.out.println("Client connected");
     } catch (SocketTimeoutException e) {
       return -1;
     } catch (IOException e) {
       e.printStackTrace();
       sockCleanup();
       return -1;
     }
   }
   try {
     userInput = (byte) in.read();
     if (userInput == -1) {
       sockCleanup();
       System.out.println("Client disconnect");
       return -1;
     }
     System.out.println("User input " + userInput);
     return userInput;
   } catch (SocketTimeoutException e) {
     return 0;
   } catch (IOException e) {
     System.out.println("Client error");
     e.printStackTrace();
     sockCleanup();
     return -1;
   }
 }
  @Test
  public void testMaxIdleWithWait() throws Exception {
    configureServer(new WaitHandler());
    Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
    client.setSoTimeout(10000);

    assertFalse(client.isClosed());

    OutputStream os = client.getOutputStream();
    InputStream is = client.getInputStream();

    os.write(
        ("GET / HTTP/1.0\r\n"
                + "host: "
                + _serverURI.getHost()
                + ":"
                + _serverURI.getPort()
                + "\r\n"
                + "connection: keep-alive\r\n"
                + "Connection: close\r\n"
                + "\r\n")
            .getBytes("utf-8"));
    os.flush();

    String in = IO.toString(is);
    int offset = in.indexOf("Hello World");
    Assert.assertTrue(offset > 0);
  }
Ejemplo n.º 27
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);
    }
  }
Ejemplo n.º 28
0
 public static void main(String args[]) throws Exception {
   // 为了简单起见,所有的异常都直接往外抛
   String host = "127.0.0.1"; // 要连接的服务端IP地址
   int port = 8899; // 要连接的服务端对应的监听端口
   // 与服务端建立连接
   Socket client = new Socket(host, port);
   // 建立连接后就可以往服务端写数据了
   Writer writer = new OutputStreamWriter(client.getOutputStream(), "UTF-8");
   writer.write("hello,server");
   writer.write("eof\n");
   writer.flush();
   // 写完以后进行读操作
   BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
   // 设置超时间为10秒
   client.setSoTimeout(10 * 1000);
   StringBuffer sb = new StringBuffer();
   String temp;
   int index;
   while ((temp = br.readLine()) != null) {
     if ((index = temp.indexOf("eof")) != -1) {
       sb.append(temp.substring(0, index));
       break;
     }
     sb.append(temp);
   }
   System.out.println("from server: " + sb);
   writer.close();
   br.close();
   client.close();
 }
Ejemplo n.º 29
0
  private String doRequests(
      String loopRequests,
      int loops,
      long pauseBetweenLoops,
      long pauseBeforeLast,
      String lastRequest)
      throws Exception {
    Socket socket = new Socket(_host, _port);
    socket.setSoTimeout(30000);

    for (int i = loops; i-- > 0; ) {
      socket.getOutputStream().write(loopRequests.getBytes(StandardCharsets.UTF_8));
      socket.getOutputStream().flush();
      if (i > 0 && pauseBetweenLoops > 0) Thread.sleep(pauseBetweenLoops);
    }
    if (pauseBeforeLast > 0) Thread.sleep(pauseBeforeLast);
    socket.getOutputStream().write(lastRequest.getBytes(StandardCharsets.UTF_8));
    socket.getOutputStream().flush();

    String response;
    if (loopRequests.contains("/unresponsive")) {
      // don't read in anything, forcing the request to time out
      Thread.sleep(_requestMaxTime * 2);
      response = IO.toString(socket.getInputStream(), StandardCharsets.UTF_8);
    } else {
      response = IO.toString(socket.getInputStream(), StandardCharsets.UTF_8);
    }
    socket.close();
    return response;
  }
  private void executeCommand(Socket client) {
    try {
      try {
        client.setSoTimeout(30000);
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintStream out = new PrintStream(client.getOutputStream());
        System.out.println("I/O setup done");

        String line = in.readLine();
        while (in.ready() && line != null) {

          System.out.println(line);
          line = in.readLine();
        }
        System.out.println(line);

        File file = new File("index.html");
        System.out.println(file.getName() + " requested.");
        sendFile(out, file);

        out.flush();
        out.close();
        in.close();
      } finally {
        client.close();
        System.out.println("A connection is closed.");
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }