Java Code Examples for java.nio.channels.SocketChannel#finishConnect()

The following examples show how to use java.nio.channels.SocketChannel#finishConnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TCPAcceptor.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public void handleConnectEvent(SelectionKey key) throws IOException {
    //1. Get the client channel
    SocketChannel client = (SocketChannel) key.channel();

    //2. Set the session status
    TCPSession session = (TCPSession) key.attachment();
    if (session == null) throw new RuntimeException("The session is null when connecting to ...");

    //3. Connect to server
    try {
        client.finishConnect();
        key.interestOps(SelectionKey.OP_READ);
        session.setStatus(SessionStatus.CLIENT_CONNECTED);
    } finally {
        session.finishConnect();
    }
}
 
Example 2
Source File: Ping.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
void processSelectedKeys() throws IOException {
  for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();) {
    
    // Retrieve the next key and remove it from the set
    SelectionKey sk = (SelectionKey)i.next();
    i.remove();
    
    // Retrieve the target and the channel
    Target t = (Target)sk.attachment();
    SocketChannel sc = (SocketChannel)sk.channel();
    
    // Attempt to complete the connection sequence
    try {
      if (sc.finishConnect()) {
        sk.cancel();
        t.connectFinish = System.currentTimeMillis();
        sc.close();
        t.done();
      }
    } catch (IOException x) {
      sc.close();
      t.failure = true;
      t.done();
    }
  }
}
 
Example 3
Source File: AbstractHTTPServer.java    From swift-k with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (true) {
        try {
            synchronized(this) {
                notifyAll();
                started = true;
            }
            SocketChannel s = channel.accept();
            s.finishConnect();
            s.configureBlocking(false);
            connectionProcessor.addChannel(s);
        }
        catch (Exception e) {
            logger.info("Caught exception in " + name + " service", e);
        }
    }
}
 
Example 4
Source File: ProxyReactorThread.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 该方法仅Reactor自身创建的主动连接使用
 */
@SuppressWarnings("unchecked")
protected void processConnectKey(SelectionKey curKey) throws IOException {
    T session = (T) curKey.attachment();
    setCurSession(session);
    SocketChannel channel = (SocketChannel) curKey.channel();
    NIOHandler curNIOHandler = session.getCurNIOHandler();
    if (curNIOHandler instanceof BackendNIOHandler) {
        BackendNIOHandler handler = (BackendNIOHandler) curNIOHandler;
        try {
            if (channel.finishConnect()) {
                handler.onConnect(curKey, session, true, null);
            }else {
                handler.onConnect(curKey, session, false, new ConnectException());
            }
        } catch (Exception e) {
            handler.onConnect(curKey, session, false, e);
        }
    }
}
 
Example 5
Source File: Connector.java    From LightComm4J with GNU Affero General Public License v3.0 6 votes vote down vote up
private void handle(SelectionKey key) {
	SocketChannel channel = (SocketChannel) key.channel();
	if (key.isConnectable()) {
		try {
			if (channel.finishConnect()) {
				//connect finish
				this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
				IoWorker worker = this.workers.get(workersIndex);
				worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
				workersIndex = (workersIndex + 1) % workers.size();
			}
		} catch (IOException e) {
			this.logger.info("[Connecter] finish connect error : " + e.toString());
			ClientParam clientParam = this.chanToParam.get(channel);
			if (clientParam.getOnConnectError() != null) {
				clientParam.getOnConnectError().onConnectError(e);
			}
			this.chanToParam.remove(channel);
			try {
				channel.close();
			} catch (IOException e1) {
				// already close
			}
		}
	}
}
 
Example 6
Source File: MultiThreadNIOEchoClient.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
/**
 * @author 梦境迷离
 * @description 连接
 * @time 2018年3月28日
 */
private void connect(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    // 如果正在连接,则完成连接
    if (channel.isConnectionPending()) {
        channel.finishConnect();
    }
    channel.configureBlocking(false);
    channel.write(ByteBuffer.wrap("Hello Server !\r\n".getBytes()));
    // 注册读事件为感兴趣的事件
    channel.register(this.selector, SelectionKey.OP_READ);
}
 
Example 7
Source File: NIOServer.java    From spring-boot-demo with MIT License 5 votes vote down vote up
private void connect(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    if (channel.finishConnect()) {
        // 成功
        log.info("成功连接了");
    } else {
        // 失败
        log.info("失败连接");
    }
}
 
Example 8
Source File: NIOAcceptor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 仅后台维护的主动创建的连接使用
 */
@SuppressWarnings("unchecked")
protected void processConnectKey(SelectionKey curKey) throws IOException {
    // only from cluster server socket
    SocketChannel curChannel = (SocketChannel) curKey.channel();
    Object obj = curKey.attachment();
    try {
        if (curChannel.finishConnect()) {
            throw new MycatException("unsupport!");
        }
    } catch (ConnectException ex) {
        LOGGER.warn("Connect failed:{}  message:{}", curChannel, ex);
    }
}
 
Example 9
Source File: LotsOfCancels.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 10
Source File: SocketIOWithTimeout.java    From stratosphere with Apache License 2.0 4 votes vote down vote up
/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 * 
 * @see SocketChannel#connect(SocketAddress)
 * @param channel
 *        - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

	boolean blockingOn = channel.isBlocking();
	if (blockingOn) {
		channel.configureBlocking(false);
	}

	try {
		if (channel.connect(endpoint)) {
			return;
		}

		long timeoutLeft = timeout;
		long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0;

		while (true) {
			// we might have to call finishConnect() more than once
			// for some channels (with user level protocols)

			int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

			if (ret > 0 && channel.finishConnect()) {
				return;
			}

			if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
				throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
			}
		}
	} catch (IOException e) {
		// javadoc for SocketChannel.connect() says channel should be closed.
		try {
			channel.close();
		} catch (IOException ignored) {
		}
		throw e;
	} finally {
		if (blockingOn && channel.isOpen()) {
			channel.configureBlocking(true);
		}
	}
}
 
Example 11
Source File: SocketIOWithTimeout.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} 
 * with a timeout.
 * 
 * @see SocketChannel#connect(SocketAddress)
 * 
 * @param channel - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, 
                    SocketAddress endpoint, int timeout) throws IOException {
  
  boolean blockingOn = channel.isBlocking();
  if (blockingOn) {
    channel.configureBlocking(false);
  }
  
  try { 
    if (channel.connect(endpoint)) {
      return;
    }

    long timeoutLeft = timeout;
    long endTime = (timeout > 0) ? (Time.now() + timeout): 0;
    
    while (true) {
      // we might have to call finishConnect() more than once
      // for some channels (with user level protocols)
      
      int ret = selector.select((SelectableChannel)channel, 
                                SelectionKey.OP_CONNECT, timeoutLeft);
      
      if (ret > 0 && channel.finishConnect()) {
        return;
      }
      
      if (ret == 0 ||
          (timeout > 0 &&  
            (timeoutLeft = (endTime - Time.now())) <= 0)) {
        throw new SocketTimeoutException(
                  timeoutExceptionString(channel, timeout, 
                                         SelectionKey.OP_CONNECT));
      }
    }
  } catch (IOException e) {
    // javadoc for SocketChannel.connect() says channel should be closed.
    try {
      channel.close();
    } catch (IOException ignored) {}
    throw e;
  } finally {
    if (blockingOn && channel.isOpen()) {
      channel.configureBlocking(true);
    }
  }
}
 
Example 12
Source File: TestSocketsDirect.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
        
    }
    
}
 
Example 13
Source File: SocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void checkSocketLocalAndRemoteAddresses(boolean setOptions) throws Exception {
    InetAddress host = InetAddress.getLocalHost();

    // Open a local server port.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    InetSocketAddress listenAddr = new InetSocketAddress(host, 0);
    try {
      ssc.socket().bind(listenAddr, 0);
    } catch (BindException e) {
      // Continuous build environment doesn't support localhost sockets.
      return;
    }
    ServerSocket ss = ssc.socket();

    // Open a socket to the local port.
    SocketChannel out = SocketChannel.open();
    out.configureBlocking(false);
    if (setOptions) {
        out.socket().setTcpNoDelay(false);
    }
    InetSocketAddress addr = new InetSocketAddress(host, ssc.socket().getLocalPort());
    out.connect(addr);
    while (!out.finishConnect()) {
        Thread.sleep(1);
    }

    SocketChannel in = ssc.accept();
    if (setOptions) {
        in.socket().setTcpNoDelay(false);
    }

    InetSocketAddress listenAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
    InetSocketAddress outRemoteAddress = (InetSocketAddress) out.socket().getRemoteSocketAddress();
    InetSocketAddress outLocalAddress = (InetSocketAddress) out.socket().getLocalSocketAddress();
    InetSocketAddress inLocalAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
    InetSocketAddress inRemoteAddress = (InetSocketAddress) in.socket().getRemoteSocketAddress();
    //System.err.println("listenAddress: " + listenAddr);
    //System.err.println("inLocalAddress: " + inLocalAddress);
    //System.err.println("inRemoteAddress: " + inRemoteAddress);
    //System.err.println("outLocalAddress: " + outLocalAddress);
    //System.err.println("outRemoteAddress: " + outRemoteAddress);

    assertEquals(outRemoteAddress.getPort(), ss.getLocalPort());
    assertEquals(inLocalAddress.getPort(), ss.getLocalPort());
    assertEquals(inRemoteAddress.getPort(), outLocalAddress.getPort());

    assertEquals(inLocalAddress.getAddress(), ss.getInetAddress());
    assertEquals(inRemoteAddress.getAddress(), ss.getInetAddress());
    assertEquals(outLocalAddress.getAddress(), ss.getInetAddress());
    assertEquals(outRemoteAddress.getAddress(), ss.getInetAddress());

    assertFalse(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertTrue(in.isConnected());
    assertTrue(in.socket().isConnected());
    assertTrue(out.socket().isConnected());
    assertTrue(out.isConnected());

    in.close();
    out.close();
    ssc.close();

    assertTrue(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertFalse(in.isConnected());
    assertFalse(in.socket().isConnected());
    assertFalse(out.socket().isConnected());
    assertFalse(out.isConnected());

    assertNull(in.socket().getRemoteSocketAddress());
    assertNull(out.socket().getRemoteSocketAddress());

    // As per docs and RI - server socket local address methods continue to return the bind()
    // addresses even after close().
    assertEquals(listenAddress, ssc.socket().getLocalSocketAddress());

    // As per docs and RI - socket local address methods return the wildcard address before
    // bind() and after close(), but the port will be the same as it was before close().
    InetSocketAddress inLocalAddressAfterClose =
            (InetSocketAddress) in.socket().getLocalSocketAddress();
    assertTrue(inLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(inLocalAddress.getPort(), inLocalAddressAfterClose.getPort());

    InetSocketAddress outLocalAddressAfterClose =
            (InetSocketAddress) out.socket().getLocalSocketAddress();
    assertTrue(outLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(outLocalAddress.getPort(), outLocalAddressAfterClose.getPort());
}
 
Example 14
Source File: LotsOfCancels.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 15
Source File: LotsOfCancels.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 16
Source File: TcpChannelHub.java    From Chronicle-Network with Apache License 2.0 4 votes vote down vote up
@Nullable
SocketChannel openSocketChannel(final InetSocketAddress socketAddress) throws IOException {
    final SocketChannel result = SocketChannel.open();
    @Nullable Selector selector = null;
    boolean failed = true;
    try {
        result.configureBlocking(false);
        Socket socket = result.socket();
        socket.setTcpNoDelay(true);
        socket.setReceiveBufferSize(tcpBufferSize);
        socket.setSendBufferSize(tcpBufferSize);
        socket.setSoTimeout(0);
        socket.setSoLinger(false, 0);
        result.connect(socketAddress);

        selector = Selector.open();
        result.register(selector, SelectionKey.OP_CONNECT);

        int select = selector.select(2500);
        if (select == 0) {
            Jvm.warn().on(TcpChannelHub.class, "Timed out attempting to connect to " + socketAddress);
            return null;
        } else {
            try {
                if (!result.finishConnect())
                    return null;

            } catch (IOException e) {
                if (DEBUG_ENABLED)
                    Jvm.debug().on(TcpChannelHub.class, "Failed to connect to " + socketAddress + " " + e);
                return null;
            }
        }
        failed = false;
        return result;

    } finally {
        Closeable.closeQuietly(selector);
        if (failed)
            Closeable.closeQuietly(result);
    }
}
 
Example 17
Source File: LotsOfCancels.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
Example 18
Source File: AESocksProxyPlugableConnectionDefault.java    From TorrentEngine with GNU General Public License v3.0 4 votes vote down vote up
protected boolean
connectSupport(
	SocketChannel 		sc )

	throws IOException
{
	if( !sc.finishConnect()){
		
		throw( new IOException( "finishConnect returned false" ));
	}
          
		// if we've got a proxy chain, now's the time to negotiate the connection
	
	AESocksProxy	proxy = socks_connection.getProxy();
	
	if ( proxy.getNextSOCKSProxyHost() != null ){
		
	}
	
	socks_connection.connected();
	
	return( true );
}
 
Example 19
Source File: TCPOutput.java    From Virtual-Hosts with GNU General Public License v3.0 4 votes vote down vote up
private void initializeConnection(String ipAndPort, InetAddress destinationAddress, int destinationPort,
                                  Packet currentPacket, TCPHeader tcpHeader, ByteBuffer responseBuffer)
        throws IOException
{
    currentPacket.swapSourceAndDestination();
    if (tcpHeader.isSYN())
    {
        SocketChannel outputChannel = SocketChannel.open();
        outputChannel.configureBlocking(false);
        vpnService.protect(outputChannel.socket());

        TCB tcb = new TCB(ipAndPort, random.nextInt(Short.MAX_VALUE + 1), tcpHeader.sequenceNumber, tcpHeader.sequenceNumber + 1,
                tcpHeader.acknowledgementNumber, outputChannel, currentPacket);
        TCB.putTCB(ipAndPort, tcb);

        try
        {
            outputChannel.connect(new InetSocketAddress(destinationAddress, destinationPort));
            if (outputChannel.finishConnect())
            {
                tcb.status = TCBStatus.SYN_RECEIVED;
                // TODO: Set MSS for receiving larger packets from the device
                currentPacket.updateTCPBuffer(responseBuffer, (byte) (TCPHeader.SYN | TCPHeader.ACK),
                        tcb.mySequenceNum, tcb.myAcknowledgementNum, 0);
                tcb.mySequenceNum++; // SYN counts as a byte
            }
            else
            {
                tcb.status = TCBStatus.SYN_SENT;
                tcpSelectorLock.lock();
                selector.wakeup();
                tcb.selectionKey = outputChannel.register(selector, SelectionKey.OP_CONNECT, tcb);
                tcpSelectorLock.unlock();
                return;
            }
        }
        catch (IOException e)
        {
            LogUtils.e(TAG, "Connection error: " + ipAndPort, e);
            currentPacket.updateTCPBuffer(responseBuffer, (byte) TCPHeader.RST, 0, tcb.myAcknowledgementNum, 0);
            TCB.closeTCB(tcb);
        }
    }
    else
    {
        currentPacket.updateTCPBuffer(responseBuffer, (byte) TCPHeader.RST,
                0, tcpHeader.sequenceNumber + 1, 0);
    }
    outputQueue.offer(responseBuffer);
}
 
Example 20
Source File: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}