@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); } }
public void receive() throws IOException, InterruptedException { Socket socket = null; socket = serverSocket.accept(); BufferedReader br = getReader(socket); for (int i = 0; i < 20; i++) { String msg = br.readLine(); System.out.println("receive:" + msg); TimeUnit.MILLISECONDS.sleep(1000); if (i == 2) { if (stopWay == SUDDEN_STOP) { System.out.println("突然终止程序"); System.exit(0); } if (stopWay == SOCKET_STOP) { System.out.println("关闭Socket并终止程序"); socket.close(); break; } if (stopWay == INPUT_STOP) { System.out.println("关闭输入流并终止程序"); socket.shutdownInput(); break; } if (stopWay == SERVERSOCKET_STOP) { System.out.println("关闭ServerSocket并终止程序"); serverSocket.close(); break; } } } if (stopWay == NATURAL_STOP) { socket.close(); serverSocket.close(); } }
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); } }
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; }
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; } } }
/** {@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; }
/** Destroys the server stored list. */ @Override public void destroy() { stopped = true; try { if (connection != null) { connection.shutdownInput(); connection.close(); connection = null; } } catch (IOException e) { } try { if (connectionReader != null) { connectionReader.close(); connectionReader = null; } } catch (IOException ex) { } if (connectionWriter != null) { connectionWriter.close(); connectionWriter = null; } }
public static void closeSocket(final Socket socket) { if (!socket.isClosed()) { try { if (!socket.isOutputShutdown()) { socket.shutdownInput(); } if (!socket.isInputShutdown()) { socket.shutdownInput(); } socket.close(); } catch (IOException e) { e.printStackTrace(); logger.severe(e.getMessage()); } } }
public void close() { try { sock.shutdownInput(); sock.shutdownOutput(); sock.close(); } catch (Exception ign) { } }
public void close() { _closed.set(true); try { _socket.shutdownInput(); } catch (IOException e) { e.printStackTrace(); } }
private void closeInputStream() { if (in != null) { try { client.shutdownInput(); } catch (Exception e) { e.printStackTrace(); } } }
private void shutdownInput(Socket socket) { if (socket == null) return; try { socket.shutdownInput(); } catch (IOException ignore) { debug(ignore); } }
@Override protected void onStop() { super.onStop(); try { socket.shutdownInput(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
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); } }
@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(); }
public void closedInput() { try { sock.shutdownInput(); } catch (IOException e) { // Ignore } synchronized (this) { inputClosed = true; if (!outputClosed) return; } try { sock.close(); } catch (IOException e) { // Ignore } }
@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 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; } } }
@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(); }
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); } } }
/** {@inheritDoc} */ public void closeChannel(SelectableChannel channel) { // channel could be either SocketChannel or ServerSocketChannel if (channel instanceof SocketChannel) { Socket socket = ((SocketChannel) channel).socket(); try { if (!socket.isInputShutdown()) socket.shutdownInput(); } catch (IOException e) { logger.log(Level.FINEST, "Unexpected exception during channel inputShutdown", e); } try { if (!socket.isOutputShutdown()) socket.shutdownOutput(); } catch (IOException e) { logger.log(Level.FINEST, "Unexpected exception during channel outputShutdown", e); } try { socket.close(); } catch (IOException e) { logger.log(Level.FINEST, "Unexpected exception during socket close", e); } } try { channel.close(); } catch (IOException e) { logger.log(Level.FINEST, "Unexpected exception during channel close", e); } if (asyncQueueReader != null) { asyncQueueReader.onClose(channel); } if (asyncQueueWriter != null) { asyncQueueWriter.onClose(channel); } }
/** @see com.thinkparity.network.NetworkConnection#disconnect() */ @Override public void disconnect() { logger.logTraceId(); logger.logInfo("{0} - Disconnect", getId()); if (isConnected()) { try { if (Boolean.FALSE == protocol.isSecure()) { socket.shutdownInput(); } } catch (final IOException iox) { logger.logWarning(iox, "{0} - Error disconnecting.", getId()); } finally { try { if (Boolean.FALSE == protocol.isSecure()) { socket.shutdownOutput(); } } catch (final IOException iox) { logger.logWarning(iox, "{0} - Error disconnecting.", getId()); } finally { try { socket.close(); } catch (final IOException iox) { logger.logWarning(iox, "{0} - Error disconnecting.", getId()); } finally { socket = null; input = null; output = null; logger.logInfo("{0} - Disconnected", getId()); connected = false; } } } } else { logger.logWarning("{0} - Is not connected.", getId()); } }
@Override public void run() { try { // PrintWriter out = new // PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.equals("exit") == false) { // appManager.messageReceived(inputLine); } else { clientSocket.shutdownInput(); clientSocket.shutdownOutput(); clientSocket.close(); SocketOperator.this.sockets.remove(clientSocket.getInetAddress()); } } } catch (IOException e) { Log.e("ReceiveConnection.run: when receiving connection ", ""); } }
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; }
@Override public void shutdownInput() throws IOException { sock.shutdownInput(); }
@Test public void testReturnSocket() throws Exception { // Force close, successfully ServerSocketChannel serverSocketChannel = SocketUtil.createServerSocketChannel( InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort(), null); serverSocketChannel.configureBlocking(true); ServerSocket serverSocket = serverSocketChannel.socket(); HttpClientSPIAgent httpClientSPIAgent = new HttpClientSPIAgent( new SPIConfiguration( null, null, serverSocket.getLocalPort(), _spiConfiguration.getBaseDir(), null, null, null), new MockRegistrationReference(new MockIntraband())); SocketChannel socketChannel = SocketChannel.open(httpClientSPIAgent.socketAddress); Socket socket = socketChannel.socket(); httpClientSPIAgent.returnSocket(socket, true); Queue<Socket> socketBlockingQueue = httpClientSPIAgent.socketBlockingQueue; Assert.assertTrue(socketBlockingQueue.isEmpty()); closePeers(socket, serverSocket); // Force close, failed without log List<LogRecord> logRecords = JDKLoggerTestUtil.configureJDKLogger(HttpClientSPIAgent.class.getName(), Level.OFF); socket = new Socket(InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort()); SocketImpl socketImpl = swapSocketImpl(socket, null); httpClientSPIAgent.returnSocket(socket, true); Assert.assertTrue(socketBlockingQueue.isEmpty()); swapSocketImpl(socket, socketImpl); closePeers(socket, serverSocket); Assert.assertTrue(logRecords.isEmpty()); // Force close, failed with log logRecords = JDKLoggerTestUtil.configureJDKLogger(HttpClientSPIAgent.class.getName(), Level.WARNING); socket = new Socket(InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort()); socketImpl = swapSocketImpl(socket, null); httpClientSPIAgent.returnSocket(socket, true); Assert.assertTrue(socketBlockingQueue.isEmpty()); swapSocketImpl(socket, socketImpl); closePeers(socket, serverSocket); Assert.assertEquals(1, logRecords.size()); LogRecord logRecord = logRecords.get(0); Throwable throwable = logRecord.getThrown(); Assert.assertSame(IOException.class, throwable.getClass()); // socket.isConnected() httpClientSPIAgent.returnSocket(new Socket(), false); Assert.assertTrue(socketBlockingQueue.isEmpty()); // socket.isInputShutdown() socketChannel = SocketChannel.open(httpClientSPIAgent.socketAddress); socket = socketChannel.socket(); socket.shutdownInput(); httpClientSPIAgent.returnSocket(socket, false); Assert.assertTrue(socketBlockingQueue.isEmpty()); closePeers(socket, serverSocket); // socket.isOutputShutdown() socketChannel = SocketChannel.open(httpClientSPIAgent.socketAddress); socket = socketChannel.socket(); socket.shutdownOutput(); httpClientSPIAgent.returnSocket(socket, false); Assert.assertTrue(socketBlockingQueue.isEmpty()); closePeers(socket, serverSocket); // Successfully return socketChannel = SocketChannel.open(httpClientSPIAgent.socketAddress); socket = socketChannel.socket(); httpClientSPIAgent.returnSocket(socket, false); Assert.assertEquals(1, socketBlockingQueue.size()); Assert.assertSame(socket, socketBlockingQueue.poll()); closePeers(socket, serverSocket); serverSocket.close(); }
@Test public void testBorrowSocket() throws Exception { // Create on empty ServerSocketChannel serverSocketChannel = SocketUtil.createServerSocketChannel( InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort(), null); serverSocketChannel.configureBlocking(true); ServerSocket serverSocket = serverSocketChannel.socket(); SPIConfiguration spiConfiguration = new SPIConfiguration( null, null, serverSocket.getLocalPort(), _spiConfiguration.getBaseDir(), null, null, null); HttpClientSPIAgent httpClientSPIAgent = new HttpClientSPIAgent( spiConfiguration, new MockRegistrationReference(new MockIntraband())); Socket socket = httpClientSPIAgent.borrowSocket(); closePeers(socket, serverSocket); // Clean up when closed Queue<Socket> socketBlockingQueue = httpClientSPIAgent.socketBlockingQueue; socketBlockingQueue.add(socket); socket = httpClientSPIAgent.borrowSocket(); closePeers(socket, serverSocket); // Clean up not connected socketBlockingQueue.add(new Socket()); socket = httpClientSPIAgent.borrowSocket(); closePeers(socket, serverSocket); // Clean up when input is shutdown socket = httpClientSPIAgent.borrowSocket(); socket.shutdownInput(); socketBlockingQueue.add(socket); socket = httpClientSPIAgent.borrowSocket(); closePeers(socket, serverSocket); socket = serverSocket.accept(); socket.close(); // Clean up when input is shutdown, failed without log List<LogRecord> logRecords = JDKLoggerTestUtil.configureJDKLogger(HttpClientSPIAgent.class.getName(), Level.OFF); socket = new Socket(InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort()); socket.shutdownInput(); SocketImpl socketImpl = swapSocketImpl(socket, null); socketBlockingQueue.add(socket); socket = httpClientSPIAgent.borrowSocket(); swapSocketImpl(socket, socketImpl); closePeers(socket, serverSocket); socket = serverSocket.accept(); socket.close(); Assert.assertTrue(logRecords.isEmpty()); // Clean up when input is shutdown, failed with log logRecords = JDKLoggerTestUtil.configureJDKLogger(HttpClientSPIAgent.class.getName(), Level.WARNING); socket = new Socket(InetAddressUtil.getLoopbackInetAddress(), _spiConfiguration.getConnectorPort()); socket.shutdownInput(); socketImpl = swapSocketImpl(socket, null); socketBlockingQueue.add(socket); socket = httpClientSPIAgent.borrowSocket(); swapSocketImpl(socket, socketImpl); closePeers(socket, serverSocket); socket = serverSocket.accept(); socket.close(); Assert.assertEquals(1, logRecords.size()); LogRecord logRecord = logRecords.get(0); Throwable throwable = logRecord.getThrown(); Assert.assertSame(IOException.class, throwable.getClass()); // Clean up when output is shutdown() socket = httpClientSPIAgent.borrowSocket(); socket.shutdownOutput(); socketBlockingQueue.add(socket); socket = httpClientSPIAgent.borrowSocket(); closePeers(socket, serverSocket); socket = serverSocket.accept(); socket.close(); // Reuse socket socket = httpClientSPIAgent.borrowSocket(); socketBlockingQueue.add(socket); Assert.assertSame(socket, httpClientSPIAgent.borrowSocket()); closePeers(socket, serverSocket); serverSocket.close(); }
@Test public void testHalfClose() throws Exception { ServerSocket connector = new ServerSocket(0); Socket client = new Socket("localhost", connector.getLocalPort()); Socket server = connector.accept(); // we can write both ways client.getOutputStream().write(1); assertEquals(1, server.getInputStream().read()); server.getOutputStream().write(1); assertEquals(1, client.getInputStream().read()); // shutdown output results in read -1 client.shutdownOutput(); assertEquals(-1, server.getInputStream().read()); // Even though EOF has been read, the server input is not seen as shutdown assertFalse(server.isInputShutdown()); // and we can read -1 again assertEquals(-1, server.getInputStream().read()); // but cannot write try { client.getOutputStream().write(1); fail("exception expected"); } catch (SocketException e) { } // but can still write in opposite direction. server.getOutputStream().write(1); assertEquals(1, client.getInputStream().read()); // server can shutdown input to match the shutdown out of client server.shutdownInput(); // now we EOF instead of reading -1 try { server.getInputStream().read(); fail("exception expected"); } catch (SocketException e) { } // but can still write in opposite direction. server.getOutputStream().write(1); assertEquals(1, client.getInputStream().read()); // client can shutdown input client.shutdownInput(); // now we EOF instead of reading -1 try { client.getInputStream().read(); fail("exception expected"); } catch (SocketException e) { } // But we can still write at the server (data which will never be read) server.getOutputStream().write(1); // and the server output is not shutdown assertFalse(server.isOutputShutdown()); // until we explictly shut it down server.shutdownOutput(); // and now we can't write try { server.getOutputStream().write(1); fail("exception expected"); } catch (SocketException e) { } // but the sockets are still open assertFalse(client.isClosed()); assertFalse(server.isClosed()); // but if we close one end client.close(); // it is seen as closed. assertTrue(client.isClosed()); // but not the other end assertFalse(server.isClosed()); // which has to be closed explictly server.close(); assertTrue(server.isClosed()); }
public void shutdownInput() throws IOException { mSocket.shutdownInput(); }