Esempio n. 1
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);
    }
  }
Esempio n. 2
0
  public static void main(String[] args) {
    try {
      // 1.创建客户端Socket,指定服务器地址和端口
      Socket socket = new Socket("localhost", 8888);

      // 2.获取输出流,向服务器端发送信息
      OutputStream os = socket.getOutputStream(); // 字节输出流
      PrintWriter pw = new PrintWriter(os); // 将输出流包装为打印流
      pw.write("用户名:alice;密码:789");
      pw.flush();
      socket.shutdownOutput(); // 关闭输出流

      // 3.获取输入流,并读取服务器端的响应信息
      InputStream is = socket.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String info = null;
      while ((info = br.readLine()) != null) {
        System.out.println("我是客户端,服务器说:" + info);
      }

      // 4.关闭资源
      br.close();
      is.close();
      pw.close();
      os.close();
      socket.close();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * there is an issue with this method: if it is called often enough, the <CODE>
  * _s.sendUrgentData(0);</CODE> method that it invokes, will force the <CODE>_s</CODE> socket to
  * close on the other end, at least on Windows systems. This behavior is due to the fact that
  * OOB data handling is problematic since there are conflicting specifications in TCP.
  * Therefore, it is required that the method is not called with high frequency (see the <CODE>
  * PDBTExecSingleCltWrkInitSrv._CHECK_PERIOD_MSECS</CODE> flag in this file.)
  *
  * @return true iff the worker is available to accept work according to all evidence.
  */
 private synchronized boolean getAvailability() {
   boolean res = _isAvail && _s != null && _s.isClosed() == false;
   if (res && _OK2SendOOB) { // work-around the OOB data issue
     // last test using OOB sending of data
     try {
       _OK2SendOOB = false; // indicates should not send OOB data until set to true
       _s.sendUrgentData(0); // unfortunately, if this method is called often enough,
       // it will cause the socket to close???
       res = true;
     } catch (IOException e) {
       // e.printStackTrace();
       utils.Messenger.getInstance()
           .msg("PDBTExecSingleCltWrkInitSrv.getAvailability(): Socket has been closed", 0);
       res = false;
       _isAvail = false; // declare availability to false as well
       // try graceful exit
       try {
         _s.shutdownOutput();
         _s.close(); // Now we can close the Socket
       } catch (IOException e2) {
         // silently ignore
       }
     }
   }
   return res;
 }
  public static void main(String[] args) throws Exception {
    // Create a mockSocket without a timeout
    final InetAddress address = InetAddress.getByName("localhost");
    final int port = 9000;

    final SocketAddress socketAddress = new InetSocketAddress(address, port);
    final Socket socket = new Socket();
    socket.setSoLinger(false, 0);

    final int timeoutMs = 1;
    socket.connect(socketAddress, timeoutMs);
    final OutputStream outputStream = socket.getOutputStream();
    String sendString = args.length == 0 ? "sendString" : args[0];
    outputStream.write(sendString.getBytes());
    socket.shutdownOutput();

    final InputStream inputStream = socket.getInputStream();
    final BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

    String str;
    while ((str = rd.readLine()) != null) {
      System.out.println(str);
    }
    rd.close();
    socket.close();
  }
Esempio n. 5
0
  public static void main(String[] args) {
    try {
      Socket socket = new Socket("localhost", 8888);

      OutputStream os = socket.getOutputStream();
      PrintWriter pw = new PrintWriter(os);
      pw.write("用户名:admin;密码:123");
      pw.flush();
      socket.shutdownOutput();

      InputStream is = socket.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String info;
      while ((info = br.readLine()) != null) {
        System.out.println("我是客户端,服务器说:" + info);
      }

      br.close();
      is.close();
      pw.close();
      os.close();
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 6
0
  /**
   * When writing a set of headers fails due to an {@code IOException}, make sure the writer is left
   * in a consistent state so the next writer also gets an {@code IOException} also instead of
   * something worse (like an {@link IllegalStateException}.
   *
   * <p>See https://github.com/square/okhttp/issues/1651
   */
  @Test
  public void socketExceptionWhileWritingHeaders() throws Exception {
    peer.setVariantAndClient(HTTP_2, false);
    peer.acceptFrame(); // SYN_STREAM.
    peer.play();

    String longString = repeat('a', Http2.INITIAL_MAX_FRAME_SIZE + 1);
    Socket socket = peer.openSocket();
    FramedConnection connection =
        new FramedConnection.Builder(true)
            .socket(socket)
            .pushObserver(IGNORE)
            .protocol(HTTP_2.getProtocol())
            .build();
    socket.shutdownOutput();
    try {
      connection.newStream(headerEntries("a", longString), false, true);
      fail();
    } catch (IOException expected) {
    }
    try {
      connection.newStream(headerEntries("b", longString), false, true);
      fail();
    } catch (IOException expected) {
    }
  }
Esempio n. 7
0
 protected void shutdownIO(final boolean read) {
   if (!isConnected()) {
     throw new NotYetConnectedException();
   }
   final SocketChannel channel = (SocketChannel) key.channel();
   try {
     final Method method =
         channel.getClass().getDeclaredMethod(read ? "shutdownInput" : "shutdownOutput");
     method.setAccessible(true);
     method.invoke(channel);
     return;
   } catch (NoSuchMethodException e) {
     logger.warn("{}", this, e);
   } catch (IllegalAccessException e) {
     logger.warn("{}", this, e);
   } catch (InvocationTargetException e) {
     logger.warn("{}", this, e);
   }
   final Socket socket = channel.socket();
   try {
     if (read) {
       socket.shutdownInput();
     } else {
       socket.shutdownOutput();
     }
   } catch (IOException e) {
     logger.warn("{}", this, e);
   }
 }
Esempio n. 8
0
 private Socket getSocket(InetAddress addr, int portNo) {
   Socket socket = null;
   if (sockets.containsKey(addr) == true) {
     socket = sockets.get(addr);
     // check the status of the socket
     if (socket.isConnected() == false
         || socket.isInputShutdown() == true
         || socket.isOutputShutdown() == true
         || socket.getPort() != portNo) {
       // if socket is not suitable, then create a new socket
       sockets.remove(addr);
       try {
         socket.shutdownInput();
         socket.shutdownOutput();
         socket.close();
         socket = new Socket(addr, portNo);
         sockets.put(addr, socket);
       } catch (IOException e) {
         Log.e("getSocket: when closing and removing", "");
       }
     }
   } else {
     try {
       socket = new Socket(addr, portNo);
       sockets.put(addr, socket);
     } catch (IOException e) {
       Log.e("getSocket: when creating", "");
     }
   }
   return socket;
 }
 public void stopOutput(Socket socket) throws IOException {
   socket.shutdownOutput();
   close(socket);
   socket = null;
   debug("Shutting down monitor");
   serverSocket = null;
 }
 /** {@inheritDoc} */
 @Override
 public AsyncSocketChannelImpl shutdown(ShutdownType how) throws IOException {
   final Socket socket = channel.socket();
   try {
     if (how == ShutdownType.READ || how == ShutdownType.BOTH) {
       if (!socket.isInputShutdown()) {
         socket.shutdownInput();
         key.selected(OP_READ);
       }
     }
     if (how == ShutdownType.WRITE || how == ShutdownType.BOTH) {
       if (!socket.isOutputShutdown()) {
         socket.shutdownOutput();
         key.selected(OP_WRITE);
       }
     }
   } catch (SocketException e) {
     if (!socket.isConnected()) {
       throw Util.initCause(new NotYetConnectedException(), e);
     }
     if (socket.isClosed()) {
       throw Util.initCause(new ClosedChannelException(), e);
     }
     throw e;
   }
   return this;
 }
Esempio n. 11
0
 private void _closeSocket() {
   synchronized (sendLock) {
     long interval = System.currentTimeMillis() - lastConnectTime;
     if (interval < connectWaitTime * 1000) {
       trace.trace("can not close socket within " + connectWaitTime + " sec");
       return;
     }
     try {
       try {
         socket.shutdownInput();
         socket.shutdownOutput();
       } catch (Exception e) {
       }
       socket.close();
     } catch (Exception e) {
     } finally {
       lastConnectTime = System.currentTimeMillis();
       connectWaitTime = 1;
       socket = null;
       listener.onClose(this);
       readBuffer.clear();
       sendBuffer.clear();
       if (State.STOPPING == _state || State.STOPPED == _state) {
         reader = null;
         return;
       }
       _state = State.STARTING;
     }
   }
 }
  @Test
  public void testPartialReadThenShutdown() throws Exception {
    server.setHandler(new PartialReaderHandler());
    server.start();

    try (final Socket socket = new Socket("localhost", connector.getLocalPort())) {
      socket.setSoTimeout(10000);

      byte[] content = new byte[32 * 4096];
      Arrays.fill(content, (byte) 88);

      OutputStream out = socket.getOutputStream();
      String header =
          "POST /?read=10 HTTP/1.1\r\n"
              + "Host: localhost\r\n"
              + "Content-Length: "
              + content.length
              + "\r\n"
              + "Content-Type: bytes\r\n"
              + "\r\n";
      byte[] h = header.getBytes(StandardCharsets.ISO_8859_1);
      out.write(h);
      out.write(content, 0, 4096);
      out.flush();
      socket.shutdownOutput();

      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      assertThat(in.readLine(), containsString("HTTP/1.1 200 OK"));
      assertThat(in.readLine(), containsString("Content-Length:"));
      assertThat(in.readLine(), containsString("Server:"));
      in.readLine();
      assertThat(in.readLine(), containsString("XXXXXXX"));
    }
  }
Esempio n. 13
0
 public void close() {
   try {
     sock.shutdownInput();
     sock.shutdownOutput();
     sock.close();
   } catch (Exception ign) {
   }
 }
 private void closeOutputStream() {
   if (out != null) {
     try {
       client.shutdownOutput();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 15
0
 public static void shutdownAndCloseQuietly(final Socket socket) {
   try {
     socket.shutdownOutput();
   } catch (IOException e) {;
   }
   try {
     socket.close();
   } catch (IOException e) {;
   }
 }
Esempio n. 16
0
 /**
  * Close the connection. This method calls close on the input and output streams and interrupts
  * any thread in the handle method. may be specialized to close sockets etc.
  *
  * @exception IOException
  */
 public void close() throws IOException {
   try {
     _completing = true;
     if (_connection instanceof Socket && !(_connection instanceof SSLSocket))
       ((Socket) _connection).shutdownOutput();
     _outputStream.close();
     _inputStream.close();
   } finally {
     if (_handlingThread != null && Thread.currentThread() != _handlingThread)
       _handlingThread.interrupt();
   }
 }
Esempio n. 17
0
  @Override
  public void close() {
    try {
      clientSocket
          .shutdownOutput(); // If we don't do this and there is still a message in the pipeline the
      // receiver will get a "connection reset"
    } catch (IOException ex) {
      throw new ProcessCommunicationException(ex);
    }

    Tools.release(inbox, outbox, clientSocket, serverSocket);
  }
 public void cancel() {
   try {
     mSocket.shutdownInput();
     mSocket.shutdownOutput();
     mmInStream.close();
     mmOutStream.close();
     mSocket.close();
     mSocket = null;
   } catch (Exception e) {
     Log.e(TAG, "close() of connect socket failed", e);
   }
 }
Esempio n. 19
0
  @Test
  public void testReset() throws Exception {
    ServerSocket connector;
    Socket client;
    Socket server;

    connector = new ServerSocket(9123);
    client = new Socket("127.0.0.1", connector.getLocalPort());
    server = connector.accept();
    client.setTcpNoDelay(true);
    client.setSoLinger(true, 0);
    server.setTcpNoDelay(true);
    server.setSoLinger(true, 0);

    client.getOutputStream().write(1);
    assertEquals(1, server.getInputStream().read());
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());

    // Server generator shutdowns output after non persistent sending response.
    server.shutdownOutput();

    // client endpoint reads EOF and shutdown input as result
    assertEquals(-1, client.getInputStream().read());
    client.shutdownInput();

    // client connection see's EOF and shutsdown output as no more requests to be sent.
    client.shutdownOutput();

    // Since input already shutdown, client also closes socket.
    client.close();

    // Server reads the EOF from client oshut and shut's down it's input
    assertEquals(-1, server.getInputStream().read());
    server.shutdownInput();

    // Since output was already shutdown, server closes
    server.close();
  }
 @Override
 protected void finalize() throws Throwable {
   try {
     if (clientSocket != null) {
       clientSocket.shutdownInput();
       clientSocket.shutdownOutput();
       clientSocket.close();
     }
     if (serverSocket != null) {
       serverSocket.close();
     }
   } catch (java.io.IOException e) {
   } finally {
     super.finalize();
   }
 }
 public void closedOutput() {
   try {
     sock.shutdownOutput();
   } catch (IOException e) {
     // Ignore
   }
   synchronized (this) {
     outputClosed = true;
     if (!inputClosed) return;
   }
   try {
     sock.close();
   } catch (IOException e) {
     // Ignore
   }
 }
Esempio n. 22
0
  @Override
  public void exit() {
    for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext(); ) {
      Socket socket = iterator.next();
      try {
        socket.shutdownInput();
        socket.shutdownOutput();
        socket.close();
      } catch (IOException e) {
      }
    }

    sockets.clear();
    this.stopListening();
    appManager = null;
    // timer.cancel();
  }
Esempio n. 23
0
 public void disconnect() {
   if (m_connConfigd) {
     if (connected) {
       try {
         if (!socket.isInputShutdown()) socket.shutdownInput();
         if (!socket.isOutputShutdown()) socket.shutdownOutput();
         socket.close();
       } catch (IOException eClose) {
         s_logger.error("Error closing TCP: " + eClose);
       }
       inputStream = null;
       outputStream = null;
       connected = false;
       socket = null;
     }
   }
 }
  @Test
  public void testShutdown() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(500);

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

    _manager.register(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes("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
    long start = System.currentTimeMillis();
    try {
      client.getInputStream().read();
      Assert.fail();
    } catch (SocketTimeoutException e) {
      assertTrue(System.currentTimeMillis() - start >= 400);
    }

    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes("UTF-8"));
    client.shutdownOutput();

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

    // Read close
    assertEquals(-1, client.getInputStream().read());
  }
Esempio n. 25
0
 private synchronized void close() throws IOException {
   data = null;
   dataLengthBuffer = null;
   if (!channel.isOpen()) return;
   try {
     socket.shutdownOutput();
   } catch (Exception e) {
   }
   if (channel.isOpen()) {
     try {
       channel.close();
     } catch (Exception e) {
     }
   }
   try {
     socket.close();
   } catch (Exception e) {
   }
 }
Esempio n. 26
0
  void close() {
    try {
      mSocket.shutdownInput();
      mSocket.shutdownOutput();

      mInstream.close();
      mInstream = null;

      mOutstream.close();
      mOutstream = null;

      mSocket.close();
      mSocket = null;
    } catch (SocketException e) {
      // the socket was reset by the client - ignore
    } catch (IOException e) {
      // ignore
    }
  }
  /** Close left-over sockets, streams and so on. */
  public void cleanup() {
    if (socket != null && socket.isConnected() && !socket.isClosed()) {
      try {
        if (socket != null && !socket.isOutputShutdown()) {
          socket.shutdownOutput();
        }
        if (socket != null && !socket.isInputShutdown()) {
          socket.shutdownInput();
        }
        if (socket != null && !socket.isClosed()) {
          socket.close();
        }

        if (bufferedInputStream != null) {
          bufferedInputStream.close();
          bufferedInputStream = null;
        }
        if (gzipInputStream != null) {
          gzipInputStream.close();
          gzipInputStream = null;
        }
        if (inputStream != null) {
          inputStream.close();
          inputStream = null;
        }
        if (gzipOutputStream != null) {
          gzipOutputStream.close();
          gzipOutputStream = null;
        }
        if (bufferedOutputStream != null) {
          bufferedOutputStream.close();
          bufferedOutputStream = null;
        }
        if (outputStream != null) {
          outputStream.close();
          outputStream = null;
        }
      } catch (Exception e) {
        baseStep.logError("Error closing socket", e);
      }
    }
  }
Esempio n. 28
0
  /**
   * Stop a forked or remote MockServer instance
   *
   * @param ipAddress IP address as string of remote MockServer (i.e. "127.0.0.1")
   * @param stopPort the stopPort for the MockServer to stop (default is HTTP port + 1)
   * @param stopWait the period to wait for MockServer to confirm it has stopped, in seconds. A
   *     value of <= 0 means do not wait for confirmation MockServer has stopped.
   */
  public boolean stop(String ipAddress, int stopPort, int stopWait) {
    if (stopPort <= 0) throw new IllegalArgumentException("Please specify a valid stopPort");

    boolean stopped = false;
    try {
      Socket socket = null;
      try {
        socket = new Socket(InetAddress.getByName(ipAddress), stopPort);

        if (socket.isConnected() && socket.isBound()) {
          OutputStream out = socket.getOutputStream();
          out.write("stop".getBytes(Charsets.UTF_8));
          socket.shutdownOutput();

          if (stopWait > 0) {
            socket.setSoTimeout(stopWait * 1000);

            logger.info("Waiting " + stopWait + " seconds for MockServer to stop");

            if (new BufferedReader(new InputStreamReader(socket.getInputStream()))
                .readLine()
                .contains("stopped")) {
              logger.info("MockServer has stopped");
              stopped = true;
            }
          } else {
            stopped = true;
          }
        }
      } finally {
        if (socket != null) {
          socket.close();
        }
      }
      TimeUnit.MILLISECONDS.sleep(100);
    } catch (Throwable t) {
      logger.error("Exception stopping MockServer", t);
      stopped = false;
    }
    return stopped;
  }
Esempio n. 29
0
  public static void main(String[] args) throws UnknownHostException, IOException {
    Socket s = new Socket("192.168.188.1", 10007);
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("1.jpg"));
    BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
    byte[] buf = new byte[1024];
    System.out.println("Client--------0");
    while ((bis.read(buf)) != -1) {
      bos.write(buf, 0, buf.length);
      bos.flush();
    }

    // 告诉服务端数据已经写完
    s.shutdownOutput();
    System.out.println("Client--------1");

    BufferedReader b = new BufferedReader(new InputStreamReader(s.getInputStream()));
    System.out.println(b.readLine());
    System.out.println("Client--------3");
    bis.close();
    s.close();
  }
 @Override
 public ChannelFuture shutdownOutput(final ChannelPromise future) {
   EventLoop loop = eventLoop();
   if (loop.inEventLoop()) {
     try {
       socket.shutdownOutput();
       future.setSuccess();
     } catch (Throwable t) {
       future.setFailure(t);
     }
   } else {
     loop.execute(
         new Runnable() {
           @Override
           public void run() {
             shutdownOutput(future);
           }
         });
   }
   return future;
 }