public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); try { InetAddress lh = InetAddress.getLocalHost(); int port = ((InetSocketAddress) (ssc.getLocalAddress())).getPort(); SocketAddress remote = new InetSocketAddress(lh, port); // Test SocketChannel shutdownXXX SocketChannel sc; sc = SocketChannel.open(remote); try { acceptAndReset(ssc); sc.shutdownInput(); sc.shutdownOutput(); } finally { sc.close(); } // Test Socket adapter shutdownXXX and isShutdownInput sc = SocketChannel.open(remote); try { acceptAndReset(ssc); boolean before = sc.socket().isInputShutdown(); sc.socket().shutdownInput(); boolean after = sc.socket().isInputShutdown(); if (before || !after) throw new RuntimeException("Before and after test failed"); sc.socket().shutdownOutput(); } finally { sc.close(); } } finally { ssc.close(); } }
@JSFunction public static Object connect(Context cx, Scriptable thisObj, Object[] args, Function func) { final TCPImpl tcp = (TCPImpl) thisObj; String host = stringArg(args, 0); int port = intArg(args, 1); boolean success = false; SocketChannel newChannel = null; try { InetSocketAddress targetAddress = new InetSocketAddress(host, port); NetworkPolicy netPolicy = tcp.getNetworkPolicy(); if ((netPolicy != null) && !netPolicy.allowConnection(targetAddress)) { log.debug("Disallowed connection to {} due to network policy", targetAddress); setErrno(Constants.EINVAL); return null; } if (log.isDebugEnabled()) { log.debug("Client connecting to {}:{}", host, port); } clearErrno(); if (tcp.boundAddress == null) { newChannel = SocketChannel.open(); } else { newChannel = SocketChannel.open(tcp.boundAddress); } tcp.clientChannel = newChannel; getRunner().registerCloseable(newChannel); tcp.clientInit(); tcp.clientChannel.connect(targetAddress); tcp.selKey = tcp.clientChannel.register( getRunner().getSelector(), SelectionKey.OP_CONNECT, new SelectorHandler() { @Override public void selected(SelectionKey key) { tcp.clientSelected(key); } }); tcp.pendingConnect = (PendingOp) cx.newObject(thisObj, PendingOp.CLASS_NAME); success = true; return tcp.pendingConnect; } catch (IOException ioe) { log.debug("Error on connect: {}", ioe); setErrno(Constants.EIO); return null; } finally { if (!success && (newChannel != null)) { getRunner().unregisterCloseable(newChannel); try { newChannel.close(); } catch (IOException ioe) { log.debug("Error closing channel that might be closed: {}", ioe); } } } }
public void start() throws IOException { System.err.println("Start"); SocketChannel control = SocketChannel.open(new InetSocketAddress("localhost", 8080)); control.write(BufferUtil.toBuffer(start)); while (control.isOpen()) { BufferUtil.clear(responseBuf); int pos = BufferUtil.flipToFill(responseBuf); if (control.read(responseBuf) == -1) control.close(); BufferUtil.flipToFlush(responseBuf, pos); } client = new SocketChannel[8]; for (int i = 0; i < client.length; i++) client[i] = SocketChannel.open(new InetSocketAddress("localhost", 8080)); }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { // create SSLEngine. SSLEngine ssle = createSSLEngine(true); /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } // Create a non-blocking socket channel. SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), serverPort); sc.connect(isa); // Complete connection. while (!sc.finishConnect()) { // waiting for the connection completed. } // handshaking handshaking(ssle, sc, null); // send out application data deliver(ssle, sc); // receive application data receive(ssle, sc); // close the socket channel. sc.close(); }
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; }
public static void main(String[] args) { try { SocketChannel socketChannel = SocketChannel.open(); SocketAddress socketAddress = new InetSocketAddress("10.0.1.12", 10741); socketChannel.connect(socketAddress); OrderFactory o = new OrderFactory(); Order order = o.SampleMessgeOrder(); order.getOrderMessage().setOrderLevel("SystemLevelCommand"); order.getOrderMessage().getOrderMethod().getMethod().get(0).setMethodName("systemStop"); order .getOrderMessage() .getOrderMethod() .getMethod() .get(0) .getParameter() .get(0) .setParameter("4"); order .getOrderMessage() .getOrderMethod() .getMethod() .get(0) .getParameter() .get(1) .setParameter("6"); NIOServer.sendData(socketChannel, order); socketChannel.socket().shutdownOutput(); } catch (Exception ex) { System.out.println("me: " + ex.getMessage()); } }
void add(Target t) { SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); boolean connected = sc.connect(t.address); t.channel = sc; t.connectStart = System.currentTimeMillis(); if (connected) { t.connectFinish = t.connectStart; sc.close(); printer.add(t); } else { synchronized (pending) { pending.add(t); } sel.wakeup(); } } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) { } } t.failure = x; printer.add(t); } }
/** @see com.DeathByCaptcha.Client#connect */ public boolean connect() throws IOException { if (null == this.channel) { this.log("OPEN"); InetAddress host = null; try { host = InetAddress.getByName(SocketClient.HOST); } catch (java.lang.Exception e) { // System.out.println(e) throw new IOException("API host not found"); } SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); try { channel.connect( new InetSocketAddress( host, SocketClient.FIRST_PORT + new Random().nextInt(SocketClient.LAST_PORT - SocketClient.FIRST_PORT + 1))); } catch (IOException e) { throw new IOException("API connection failed"); } this.channel = channel; } return null != this.channel; }
/** * ���һ��Socketͨ�������Ը�ͨ����һЩ��ʼ���Ĺ��� * * @param ip ���ӵķ�������ip * @param port ���ӵķ������Ķ˿ں� * @throws IOException */ public void initClient(String ip, int port) { // ���һ��Socketͨ�� SocketChannel channel = null; try { channel = SocketChannel.open(); // ����ͨ��Ϊ������ channel.configureBlocking(false); // ���һ��ͨ�������� this.selector = Selector.open(); // �ͻ������ӷ�����,��ʵ����ִ�в�û��ʵ�����ӣ���Ҫ��listen���������е� // ��channel.finishConnect();����������� channel.connect(new InetSocketAddress(ip, port)); // ��ͨ����������ͨ������Ϊ��ͨ��ע��SelectionKey.OP_CONNECT�¼��� channel.register(selector, SelectionKey.OP_CONNECT); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); if (channel != null) { try { channel.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
@Override public void run() { try { // first create unconnected socket, so it can be closed while connecting GlobalData.socketChannel = SocketChannel.open(); GlobalData.socketChannel.connect(new InetSocketAddress(host, port)); } catch (AsynchronousCloseException ace) { // socket was closed (i.e. cancel button was hit) Log.d(TAG, "async close exception"); return; } catch (IOException ioe) { // connecting failed GlobalData.connectorMsgHandler.sendMessage( GlobalData.connectorMsgHandler.obtainMessage( Connector.CONNECT_ERR_MSG, ioe.getMessage())); return; } catch (Exception e) { // connection failed GlobalData.connectorMsgHandler.sendMessage( GlobalData.connectorMsgHandler.obtainMessage(Connector.CONNECT_ERR_MSG, e.getMessage())); return; } // alrighty GlobalData.connectorMsgHandler.sendEmptyMessage(Connector.CONNECT_OK_MSG); }
public SentMessageService(String title, String content) { try { SocketChannel socketChannel = SocketChannel.open(); SocketAddress socketAddress = new InetSocketAddress("10.0.1.25", 10240); socketChannel.connect(socketAddress); OrderFactory o = new OrderFactory(); Order order = o.SampleMessgeOrder(); order .getOrderMessage() .getOrderMethod() .getMethod() .get(0) .getParameter() .get(0) .setParameter(title); order .getOrderMessage() .getOrderMethod() .getMethod() .get(0) .getParameter() .get(1) .setParameter(content); NIOServer.sendData(socketChannel, order); socketChannel.socket().shutdownOutput(); } catch (Exception ex) { System.out.println("me: " + ex.getMessage()); } }
// 建立一个SocketChannel此时还未连接 private static SocketChannel newSocket() { try { return SocketChannel.open(); } catch (IOException e) { throw new ChannelException("Failed to open a socket.", e); } }
/** * @throws IOException * @throws InterruptedException */ protected synchronized void reConnect() throws IOException, InterruptedException { // 0. Don't send connect request if it is connecting. if (isNotConnected()) { SocketAddress remoteAddress = new InetSocketAddress(this.host, this.port); // 1. Create socket channel SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.socket().setTcpNoDelay(true); channel.socket().setReceiveBufferSize(48 * 1024); channel.socket().setSendBufferSize(48 * 1024); channel.connect(remoteAddress); // 2. Create NioSession for each client connection IoSession client = new DefaultIoSession().setChannel(channel).setIoWork(ioWorker).setEventWork(eventWorker); // 3. Register event reactorManager.nextReactor().registerSession(client, SelectionKey.OP_CONNECT); // 4. Wait to connect if (!client.waitToConnect(connectTimeout, TimeUnit.MILLISECONDS)) { client.close(); // TODO:asyncClose(); throw new IOException("connect timed out to " + this.host + ":" + this.port); } IoSession.Status status = client.getStatus(); if (status == IoSession.Status.NOT_CONNECT || status == IoSession.Status.CLOSED) { client.close(); // TODO:.asyncClose(); throw new IOException("connect failed to " + this.host + ":" + this.port); } this.session = client; } }
/** * Create a new socket to the data port and send a block request. The returned value is the * response from the server. */ private DataServerMessage request(final BlockInfo block, final long offset, final long length) throws IOException, TException { DataServerMessage sendMsg = DataServerMessage.createBlockRequestMessage(block.blockId, offset, length); SocketChannel socketChannel = SocketChannel.open( new InetSocketAddress( block.getLocations().get(0).getWorkerAddress().getHost(), block.getLocations().get(0).getWorkerAddress().getDataPort())); try { while (!sendMsg.finishSending()) { sendMsg.send(socketChannel); } DataServerMessage recvMsg = DataServerMessage.createBlockResponseMessage(false, block.blockId, offset, length, null); while (!recvMsg.isMessageReady()) { int numRead = recvMsg.recv(socketChannel); if (numRead == -1) { break; } } return recvMsg; } finally { socketChannel.close(); } }
public SocketChannel getChannel() throws IOException { if (channel == null) { channel = SocketChannel.open(); channel.configureBlocking(false); } return channel; }
public String connect(final String ipAddress, final int port) { for (int i = 0; i <= _retry; i++) { SocketChannel sch = null; try { if (s_logger.isDebugEnabled()) { s_logger.debug("Trying to connect to " + ipAddress); } sch = SocketChannel.open(); sch.configureBlocking(true); final InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; } catch (final IOException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Could not connect to " + ipAddress); } } finally { if (sch != null) { try { sch.close(); } catch (final IOException e) { } } } try { Thread.sleep(_sleep); } catch (final InterruptedException e) { } } s_logger.debug("Unable to logon to " + ipAddress); return "Unable to connect"; }
public void addTarget(Target target) { // 向targets队列中加入一个任务 SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(target.address); target.channel = socketChannel; target.connectStart = System.currentTimeMillis(); synchronized (targets) { targets.add(target); } selector.wakeup(); } catch (Exception x) { if (socketChannel != null) { try { socketChannel.close(); } catch (IOException xx) { } } target.failure = x; addFinishedTarget(target); } }
private void connectSender() throws IOException { sender = SocketChannel.open(); sender.configureBlocking(true); sender.socket().setTcpNoDelay(true); senderThread = new SenderThread(); senderThread.start(); }
/** * Construct a memcached connection. * * @param bufSize the size of the buffer used for reading from the server * @param f the factory that will provide an operation queue * @param a the addresses of the servers to connect to * @throws IOException if a connection attempt fails early */ public MemcachedConnection(int bufSize, ConnectionFactory f, List<InetSocketAddress> a) throws IOException { reconnectQueue = new TreeMap<Long, MemcachedNode>(); addedQueue = new ConcurrentLinkedQueue<MemcachedNode>(); selector = Selector.open(); List<MemcachedNode> connections = new ArrayList<MemcachedNode>(a.size()); for (SocketAddress sa : a) { SocketChannel ch = SocketChannel.open(); ch.configureBlocking(false); MemcachedNode qa = f.createMemcachedNode(sa, ch, bufSize); int ops = 0; if (ch.connect(sa)) { getLogger().info("Connected to %s immediately", qa); qa.connected(); assert ch.isConnected(); } else { getLogger().info("Added %s to connect queue", qa); ops = SelectionKey.OP_CONNECT; } qa.setSk(ch.register(selector, ops, qa)); assert ch.isConnected() || qa.getSk().interestOps() == SelectionKey.OP_CONNECT : "Not connected, and not wanting to connect"; connections.add(qa); } locator = f.createLocator(connections); }
/* ------------------------------------------------------------ */ public void startConnection(HttpDestination destination) throws IOException { SocketChannel channel = null; try { channel = SocketChannel.open(); Address address = destination.isProxied() ? destination.getProxy() : destination.getAddress(); channel.socket().setTcpNoDelay(true); if (_httpClient.isConnectBlocking()) { channel.socket().connect(address.toSocketAddress(), _httpClient.getConnectTimeout()); channel.configureBlocking(false); _selectorManager.register(channel, destination); } else { channel.configureBlocking(false); channel.connect(address.toSocketAddress()); _selectorManager.register(channel, destination); ConnectTimeout connectTimeout = new ConnectTimeout(channel, destination); _httpClient.schedule(connectTimeout, _httpClient.getConnectTimeout()); _connectingChannels.put(channel, connectTimeout); } } catch (UnresolvedAddressException ex) { if (channel != null) channel.close(); destination.onConnectionFailed(ex); } catch (IOException ex) { if (channel != null) channel.close(); destination.onConnectionFailed(ex); } }
private void attemptReconnects() throws IOException { final long now = System.currentTimeMillis(); final Map<MemcachedNode, Boolean> seen = new IdentityHashMap<MemcachedNode, Boolean>(); for (Iterator<MemcachedNode> i = reconnectQueue.headMap(now).values().iterator(); i.hasNext(); ) { final MemcachedNode qa = i.next(); i.remove(); if (!seen.containsKey(qa)) { seen.put(qa, Boolean.TRUE); getLogger().info("Reconnecting %s", qa); final SocketChannel ch = SocketChannel.open(); ch.configureBlocking(false); int ops = 0; if (ch.connect(qa.getSocketAddress())) { getLogger().info("Immediately reconnected to %s", qa); assert ch.isConnected(); } else { ops = SelectionKey.OP_CONNECT; } qa.registerChannel(ch, ch.register(selector, ops, qa)); assert qa.getChannel() == ch : "Channel was lost."; } else { getLogger().debug("Skipping duplicate reconnect request for %s", qa); } } }
public static void main(String[] args) throws IOException { SocketChannel socketChannel = SocketChannel.open(); // 如果设置非阻塞模式,就可以在异步模式下调用connect(), read() 和write()了。可以进一步和Selector配合。之后章节会涉及 // socketChannel.configureBlocking(false); // 这个需要127.0.0.1的9999端口有进程在监听了,之后会将用ServerSocketChannel监听端口,做服务端 socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999)); ByteBuffer buf = ByteBuffer.allocate(48); // 剩下的读写都可以参考fileChannel // 非阻塞模式时候可以如下等待 // while(! socketChannel.finishConnect() ){ // wait, or do something else... // } // 读取数据 // int bytesRead = socketChannel.read(buf); // System.out.println(bytesRead); // 写入数据 String newData = "New String to write to file..." + System.currentTimeMillis(); buf.clear(); buf.put(newData.getBytes()); buf.flip(); System.out.println("Start send message"); while (buf.hasRemaining()) { socketChannel.write(buf); } System.out.println("Finish send"); }
/** * Test of a large write on a socket to understand what happens when the write is greater than the * combined size of the client send buffer and the server receive buffer and the server side of * the socket is either not accepted or already shutdown. * * @throws IOException * @throws InterruptedException */ public void testDirectSockets_largeWrite_NotAccepted() throws IOException, InterruptedException { final Random r = new Random(); // Get a socket addresss for an unused port. final InetSocketAddress serverAddr = new InetSocketAddress(getPort(0)); // First our ServerSocket final ServerSocket ss = new ServerSocket(); try { // Size of the server socket receive buffer. final int receiveBufferSize = ss.getReceiveBufferSize(); // Allocate buffer twice as large as the receive buffer. final byte[] largeBuffer = new byte[receiveBufferSize * 10]; if (log.isInfoEnabled()) { log.info( "receiveBufferSize=" + receiveBufferSize + ", largeBufferSize=" + largeBuffer.length); } // fill buffer with random data. r.nextBytes(largeBuffer); // bind the ServerSocket to the specified port. ss.bind(serverAddr); // Now the first Client SocketChannel final SocketChannel cs = SocketChannel.open(); try { /* * Note: true if connection made. false if connection in * progress. */ final boolean immediate = cs.connect(serverAddr); if (!immediate) { // Did not connect immediately, so finish connect now. if (!cs.finishConnect()) { fail("Did not connect."); } } /* * Attempt to write data. The server socket is not yet accepted. * This should hit a timeout. */ assertTimeout(10L, TimeUnit.SECONDS, new WriteBufferTask(cs, ByteBuffer.wrap(largeBuffer))); accept(ss); } finally { cs.close(); } } finally { ss.close(); } }
private void reconnect() { FVLog.log(LogLevel.INFO, this, "trying to reconnect to ", this.hostname, ":", this.port); // reset our state to unconnected (might be a NOOP) this.isConnected = false; this.msgStream = null; // try to connect socket to controller try { if (this.sock != null) // note that this automatically unregisters from selector this.sock.close(); this.sock = SocketChannel.open(); sock.configureBlocking(false); // set to non-blocking InetSocketAddress addr = new InetSocketAddress(hostname, port); if (addr.isUnresolved()) { FVLog.log(LogLevel.INFO, this, "retrying: failed to resolve hostname: ", hostname); this.reconnectLater(); return; } this.isConnected = this.sock.connect(addr); // try to connect // register into event loop this.loop.register(this.sock, SelectionKey.OP_CONNECT, this); } catch (IOException e) { FVLog.log(LogLevel.CRIT, this, "Trying to reconnect; trying later; got : ", e); this.reconnectLater(); } }
/** * Starts a new Thread and connects to server * * @throws IOException */ public Thread connect() throws IOException { this.running = true; this.readyState = WEBSOCKET_STATE_CONNECTING; // open socket socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); // set address socketChannel.connect(new InetSocketAddress(uri.getHost(), port)); // start a thread to make connection // More info: // http://groups.google.com/group/android-developers/browse_thread/thread/45a8b53e9bf60d82 // http://stackoverflow.com/questions/2879455/android-2-2-and-bad-address-family-on-socket-connect System.setProperty("java.net.preferIPv4Stack", "true"); System.setProperty("java.net.preferIPv6Addresses", "false"); selector = Selector.open(); socketChannel.register(selector, SelectionKey.OP_CONNECT); Log.v("websocket", "Starting a new thread to manage data reading/writing"); Thread th = new Thread(this); th.start(); // return thread object for explicit closing, if needed return th; }
boolean initiateConnection(Connection conn_, Peer peer) { TCPConnection conn = (TCPConnection) conn_; try { SocketChannel channel = SocketChannel.open(); InetSocketAddress localAddress = new InetSocketAddress(conn.host_id, 0); channel.socket().bind(localAddress); channel.configureBlocking(false); try { InetSocketAddress remoteAddress = new InetSocketAddress(peer.host(), peer.port()); if (channel.connect(remoteAddress)) { // This only happens on Solaris when connecting locally logger.log(Level.FINEST, "Connected!"); conn.state = Connection.State.connected_out; conn.channel = channel; selector.wakeup(); channel.register(selector, SelectionKey.OP_READ, conn); initiateCER(conn); return true; } } catch (java.nio.channels.UnresolvedAddressException ex) { channel.close(); return false; } conn.state = Connection.State.connecting; conn.channel = channel; selector.wakeup(); channel.register(selector, SelectionKey.OP_CONNECT, conn); } catch (java.io.IOException ex) { logger.log( Level.WARNING, "java.io.IOException caught while initiating connection to '" + peer.host() + "'.", ex); } return true; }
J2SeTcpConnection( J2SeTcpConnectionFactory paramJ2SeTcpConnectionFactory, String paramString, int paramInt) throws IOException { this.channel = new CountingByteChannel( SocketChannel.open(new InetSocketAddress(paramString, paramInt)), paramJ2SeTcpConnectionFactory); }
public void run() { try { SocketChannel sc = SocketChannel.open(); InetSocketAddress sinaAddr = new InetSocketAddress("sina.com", 80); sc.socket().connect(sinaAddr); // init a selector via helper class selector provider Selector aSel = SelectorProvider.provider().openSelector(); Socket soc = new Socket("host", 80); soc.getChannel().register(aSel, SelectionKey.OP_ACCEPT); // init a channel for server socket. method 1 ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(true); // method 2, get server socket first, then init its channel ServerSocket ss = new ServerSocket(); ServerSocketChannel ssc2 = ss.getChannel(); // set socket channel as non blocking. ssc.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress("localhost", 9999); ssc.socket().bind(isa); SelectionKey acceptKey = ssc.register(aSel, SelectionKey.OP_ACCEPT); int keysAdded = 0; while ((keysAdded = aSel.select()) > 0) { Set readyKeys = aSel.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); ServerSocketChannel n = (ServerSocketChannel) sk.channel(); // now we got a new socket and its channel after accept in server Socket s = n.accept().socket(); SocketChannel socketChannel = s.getChannel(); socketChannel.register(aSel, SelectionKey.OP_READ); } } } catch (Exception e) { } }
/** blocks until connected */ @Override SelectableChannel doConnect() throws IOException, InterruptedException { boolean success = false; final SocketChannel socketChannel = SocketChannel.open(); try { socketChannel.configureBlocking(false); socketChannel.socket().setReuseAddress(true); socketChannel.socket().setSoLinger(false, 0); socketChannel.socket().setSoTimeout(0); socketChannel.socket().setTcpNoDelay(true); try { socketChannel.connect(details.address()); } catch (UnresolvedAddressException e) { this.connectLater(); } // Under experiment, the concoction was found to be more successful if we // paused before registering the OP_CONNECT Thread.sleep(10); // the registration has be be run on the same thread as the selector addPendingRegistration( new Runnable() { @Override public void run() { final Attached attached = new Attached(); attached.connector = ClientConnector.this; try { socketChannel.register(selector, OP_CONNECT, attached); } catch (ClosedChannelException e) { if (socketChannel.isOpen()) LOG.error("", e); } } }); selector.wakeup(); success = true; return socketChannel; } finally { if (!success) { try { try { socketChannel.socket().close(); } catch (Exception e) { LOG.error("", e); } socketChannel.close(); } catch (IOException e) { LOG.error("", e); } } } }
@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); } }