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

The following examples show how to use java.nio.channels.SocketChannel#isConnectionPending() . 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: ExtendedWorker.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
protected void connectOP(SelectionKey key) throws IOException {
	U.must(key.isConnectable());

	SocketChannel socketChannel = (SocketChannel) key.channel();
	if (!socketChannel.isConnectionPending()) {
		// not ready to retrieve the connection status
		return;
	}

	ConnectionTarget target = (ConnectionTarget) key.attachment();

	boolean ready;
	try {
		ready = socketChannel.finishConnect();
		U.must(ready, "Expected an established connection!");

		Log.info("Connected", "address", target.addr);

		connected.add(new RapidoidChannel(socketChannel, true, target.protocol, target.holder,
			target.reconnecting, target.state));

	} catch (ConnectException e) {
		retryConnecting(target);
	}
}
 
Example 2
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 3
Source File: TCPClientReadThread.java    From game-server with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void run() {
	try {
		while (true) {
			selector.select();
			Iterator ite = selector.selectedKeys().iterator();
			while (ite.hasNext()) {

				SelectionKey key = (SelectionKey) ite.next();
				ite.remove();
				if (key.isConnectable()) {
					SocketChannel channel = (SocketChannel) key.channel();
					if (channel.isConnectionPending()) {
						channel.finishConnect();

					}
					channel.configureBlocking(false);
					channel.register(selector, SelectionKey.OP_READ);

				} else {
					if (key.isReadable()) {
						read(key);
					}
				}

			}
		}

	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 4
Source File: NIOConnector.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean finishConnect(ClosableConnection c, SocketChannel channel) throws IOException {
	if (channel.isConnectionPending()) {
		channel.finishConnect();
		c.setLocalPort(channel.socket().getLocalPort());
		return true;
	} else {
		return false;
	}
}
 
Example 5
Source File: NIOConnector.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private boolean finishConnect(AbstractConnection c, SocketChannel channel)
        throws IOException {
    if (channel.isConnectionPending()) {
        channel.finishConnect();

        c.setLocalPort(channel.socket().getLocalPort());
        return true;
    } else {
        return false;
    }
}
 
Example 6
Source File: ConnectionManager.java    From defense-solutions-proofs-of-concept with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to finish a connection
 * @param key
 */
void finishConnection(SelectionKey key)
{
	SocketChannel chan = (SocketChannel) key.channel();
	Session session = socChanMap.get(chan);

	if (chan.isConnectionPending())
	{
		try
		{
			if (session.getConnection().finishConnect())
			{
				session.halfConnected();
				session.login();
			}
			else
			{
				session.connecting();
			}
		}
		catch (IOException e)
		{
			session.markForRemoval();
			key.cancel();
			e.printStackTrace();
		}
	}
}
 
Example 7
Source File: NIOConnector.java    From Mycat-NIO with Apache License 2.0 5 votes vote down vote up
private boolean finishConnect(Connection c, SocketChannel channel) throws IOException {
	System.out.println("----------------finishConnect-----------------");
	if (channel.isConnectionPending()) {
		System.out.println("----------------finishConnect-isConnectionPending-----------------");
		channel.finishConnect();
		// c.setLocalPort(channel.socket().getLocalPort());
		return true;
	} else {
		return false;
	}
}
 
Example 8
Source File: SelectorThread.java    From sctp with GNU Affero General Public License v3.0 5 votes vote down vote up
private void finishConnectionTcp(SelectionKey key) throws IOException {

		AssociationImpl association = (AssociationImpl) key.attachment();

		try {
			SocketChannel socketChannel = (SocketChannel) key.channel();
			if (socketChannel.isConnectionPending()) {

				// TODO Loop? Or may be sleep for while?
				while (socketChannel.isConnectionPending()) {
					socketChannel.finishConnect();
				}
			}

			if (logger.isInfoEnabled()) {
				logger.info(String.format("Association=%s connected to=%s", association.getName(), socketChannel.getRemoteAddress()));
			}

			// Register an interest in writing on this channel
			key.interestOps(SelectionKey.OP_READ);

			AssocChangeEvent ace = AssocChangeEvent.COMM_UP;
			AssociationChangeNotification2 acn = new AssociationChangeNotification2(ace);
			association.associationHandler.handleNotification(acn, association);

		} catch (Exception e) {
			logger.error(String.format("Exception while finishing connection for Association=%s", association.getName()), e);

			association.scheduleConnect();
		}
	}
 
Example 9
Source File: AbstractSocketChannelBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void internalReceiveCommand(String itemName, Command command) {
    P provider = findFirstMatchingBindingProvider(itemName);

    if (provider == null) {
        logger.warn("Cannot find matching binding provider [itemName={}, command={}]", itemName, command);
        return;
    }

    if (command != null) {
        List<Command> commands = provider.getQualifiedCommands(itemName, command);

        for (Command someCommand : commands) {

            Channel theChannel = null;
            if (useAddressMask && (provider.getHost(itemName, someCommand).equals("*")
                    || provider.getPortAsString(itemName, someCommand).equals("*"))) {
                theChannel = channels.get(itemName, someCommand, provider.getDirection(itemName, someCommand),
                        provider.getHost(itemName, someCommand), provider.getPortAsString(itemName, someCommand));
            } else {
                theChannel = channels.get(itemName, someCommand, provider.getDirection(itemName, someCommand),
                        new InetSocketAddress(provider.getHost(itemName, someCommand),
                                provider.getPort(itemName, someCommand)));
            }

            SocketChannel theSocketChannel = null;
            if (theChannel != null) {
                theSocketChannel = theChannel.channel;
            }

            if (theSocketChannel != null) {

                boolean result = internalReceiveChanneledCommand(itemName, someCommand, theChannel,
                        command.toString());

                if (!theSocketChannel.isConnected()
                        && !(useAddressMask && (provider.getHost(itemName, someCommand).equals("*")
                                || provider.getPortAsString(itemName, someCommand).equals("*")))) {

                    logger.warn(
                            "The channel for {} has a connection problem. Data will be queued to the new channel when it is successfully set up.",
                            theChannel.remote);

                    if (!theSocketChannel.isConnectionPending() || !theSocketChannel.isOpen()) {

                        Scheduler scheduler = null;
                        try {
                            scheduler = StdSchedulerFactory.getDefaultScheduler();
                        } catch (SchedulerException e1) {
                            logger.warn("An exception occurred while getting the Quartz scheduler: {}",
                                    e1.getMessage());
                        }

                        JobDataMap map = new JobDataMap();
                        map.put("Channel", theChannel);
                        map.put("Binding", this);

                        JobDetail job = newJob(ReconnectJob.class)
                                .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-"
                                        + Long.toString(System.currentTimeMillis()), this.toString())
                                .usingJobData(map).build();

                        Trigger trigger = newTrigger()
                                .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-"
                                        + Long.toString(System.currentTimeMillis()), this.toString())
                                .startNow().build();

                        try {
                            if (job != null && trigger != null) {
                                if (!theChannel.isReconnecting) {
                                    theChannel.isReconnecting = true;
                                    scheduler.scheduleJob(job, trigger);
                                }
                            }
                        } catch (SchedulerException e) {
                            logger.warn(
                                    "An exception occurred while scheduling a job with the Quartz Scheduler {}",
                                    e.getMessage());
                        }
                    }
                }

                if (result) {
                    List<Class<? extends State>> stateTypeList = provider.getAcceptedDataTypes(itemName,
                            someCommand);
                    State newState = createStateFromString(stateTypeList, command.toString());

                    if (newState != null) {
                        eventPublisher.postUpdate(itemName, newState);
                    }
                }
            } else {
                logger.warn("There is no channel that services [itemName={}, command={}]", itemName, command);
            }
        }
    }
}
 
Example 10
Source File: AbstractSocketHandler.java    From localization_nifi with Apache License 2.0 3 votes vote down vote up
/**
 * This will connect the channel; if it is in a pending state then this will finish
 * establishing the connection. Finally the socket handler is registered with this
 * channel.
 *
 * @throws IOException if anything goes wrong during the connection establishment
 * or registering of the handler
 */
private void connect(SelectionKey selectionKey) throws IOException {
    SocketChannel clientChannel = (SocketChannel) selectionKey.channel();
    if (clientChannel.isConnectionPending()) {
        clientChannel.finishConnect();
    }
    clientChannel.register(AbstractSocketHandler.this.selector, SelectionKey.OP_READ);
}
 
Example 11
Source File: AbstractSocketHandler.java    From nifi with Apache License 2.0 3 votes vote down vote up
/**
 * This will connect the channel; if it is in a pending state then this will finish
 * establishing the connection. Finally the socket handler is registered with this
 * channel.
 *
 * @throws IOException if anything goes wrong during the connection establishment
 * or registering of the handler
 */
private void connect(SelectionKey selectionKey) throws IOException {
    SocketChannel clientChannel = (SocketChannel) selectionKey.channel();
    if (clientChannel.isConnectionPending()) {
        clientChannel.finishConnect();
    }
    clientChannel.register(AbstractSocketHandler.this.selector, SelectionKey.OP_READ);
}