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

The following examples show how to use java.nio.channels.SocketChannel#open() . 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: RemotingUtil.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) {
    SocketChannel sc = null;
    try {
        sc = SocketChannel.open();
        sc.configureBlocking(true);
        sc.socket().setSoLinger(false, -1);
        sc.socket().setTcpNoDelay(true);
        sc.socket().setReceiveBufferSize(1024 * 64);
        sc.socket().setSendBufferSize(1024 * 64);
        sc.socket().connect(remote, timeoutMillis);
        sc.configureBlocking(false);
        return sc;
    } catch (Exception e) {
        if (sc != null) {
            try {
                sc.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    return null;
}
 
Example 2
Source File: KafkaBackendConnectionFactory.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public BackendConnection make(PhysicalNode physicalNode, BackendCallback callback, Object attachement)
		throws IOException {

	String host = physicalNode.getHost();
	int port = physicalNode.getPort();
	
	SocketChannel channel = SocketChannel.open();
	channel.configureBlocking(false);

	KafkaBackendConnection c = new KafkaBackendConnection( channel );
	NetSystem.getInstance().setSocketParams(c, false);

	// 设置NIOHandlers
	c.setHandler( new KafkaBackendConnectionHandler() );
	c.setHost( host );
	c.setPort( port );
	c.setPhysicalNode( physicalNode );
	c.setCallback( callback );
	c.setAttachement( attachement );
	c.setIdleTimeout( NetSystem.getInstance().getNetConfig().getBackendIdleTimeout() );
	
	// 连接 
	NetSystem.getInstance().getConnector().postConnect(c);
	return c;
}
 
Example 3
Source File: RemotingUtil.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) {
    SocketChannel sc = null;
    try {
        sc = SocketChannel.open();
        sc.configureBlocking(true);
        sc.socket().setSoLinger(false, -1);
        sc.socket().setTcpNoDelay(true);
        sc.socket().setReceiveBufferSize(1024 * 64);
        sc.socket().setSendBufferSize(1024 * 64);
        sc.socket().connect(remote, timeoutMillis);
        sc.configureBlocking(false);
        return sc;
    } catch (Exception e) {
        if (sc != null) {
            try {
                sc.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    return null;
}
 
Example 4
Source File: InheritedChannelNotServerSocket.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public synchronized Channel inheritedChannel() throws IOException {
    System.err.println("SP.inheritedChannel");
    if (channel == null) {
        channel = SocketChannel.open();
        Socket socket = channel.socket();
        System.err.println("socket = " + socket);

        /*
         * Notify test that inherited channel was created.
         */
        try {
            System.err.println("notify test...");
            Registry registry =
                LocateRegistry.getRegistry(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT);
            Callback obj = (Callback) registry.lookup("Callback");
            obj.notifyTest();
        } catch (NotBoundException nbe) {
            throw (IOException)
                new IOException("callback object not bound").
                    initCause(nbe);
        }
    }
    return channel;
}
 
Example 5
Source File: ShutdownInput.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    InetAddress iaddr = InetAddress.getLocalHost();

    try ( ServerSocket ss = new ServerSocket(0);
          Socket s1 = new Socket(iaddr, ss.getLocalPort());
          Socket s2 = ss.accept() ) {

        test(s1, s2, "Testing NET");
    }

    // check the NIO socket adapter
    try (ServerSocketChannel sc = ServerSocketChannel.open().bind(null);
         SocketChannel s1 = SocketChannel.open(
                 new InetSocketAddress(iaddr, sc.socket().getLocalPort()));
         SocketChannel s2 = sc.accept() ) {

        test(s1.socket(), s2.socket(), "Testing NIO");
    }

    if (failed) {
        throw new RuntimeException("Failed: check output");
    }
}
 
Example 6
Source File: RemotingUtil.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) {
    SocketChannel sc = null;
    try {
        sc = SocketChannel.open();
        sc.configureBlocking(true);
        sc.socket().setSoLinger(false, -1);
        sc.socket().setTcpNoDelay(true);
        sc.socket().setReceiveBufferSize(1024 * 64);
        sc.socket().setSendBufferSize(1024 * 64);
        sc.socket().connect(remote, timeoutMillis);
        sc.configureBlocking(false);
        return sc;
    } catch (Exception e) {
        if (sc != null) {
            try {
                sc.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    return null;
}
 
Example 7
Source File: DataTransferClientHelper.java    From rubix with Apache License 2.0 5 votes vote down vote up
public static SocketChannel createDataTransferClient(String remoteNodeName, Configuration conf)
    throws IOException
{
  SocketAddress sad = new InetSocketAddress(remoteNodeName, CacheConfig.getDataTransferServerPort(conf));
  SocketChannel sc = SocketChannel.open();
  sc.socket().setSoTimeout(CacheConfig.getClientReadTimeout(conf));
  sc.configureBlocking(true);
  sc.socket().connect(sad, CacheConfig.getServerConnectTimeout(conf));
  return sc;
}
 
Example 8
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPortForward() throws IOException {

  server.expect().withPath("/api/v1/namespaces/test/pods/pod1/portforward?ports=123")
    .andUpgradeToWebSocket()
    .open()
    .waitFor(10).andEmit(portForwardEncode(true, "12")) // data channel info
    .waitFor(10).andEmit(portForwardEncode(false, "12")) // error channel info
    .waitFor(10).andEmit(portForwardEncode(true, "Hell"))
    .waitFor(10).andEmit(portForwardEncode(true, "o World"))
    .done()
    .once();

  KubernetesClient client = server.getClient();

  try(LocalPortForward portForward = client.pods().withName("pod1").portForward(123)) {
    int localPort = portForward.getLocalPort();
    SocketChannel channel = SocketChannel.open();
    assertTrue(channel.connect(new InetSocketAddress("localhost", localPort)));

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    int read;
    do {
      read = channel.read(buffer);
    } while(read >= 0);
    buffer.flip();
    String data = ByteString.of(buffer).utf8();
    assertEquals("Hello World", data);
    assertFalse(portForward.errorOccurred());
    assertEquals(portForward.getClientThrowables().size(), 0);
    assertEquals(portForward.getServerThrowables().size(), 0);
  }

}
 
Example 9
Source File: StandardSocketChannel.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
public static StandardSocketChannel open(String address, int port,
                                         int contimeout, int timeout)
        throws IOException
{
    InetSocketAddress socketAddress = new InetSocketAddress(address, port);
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.socket().connect(socketAddress, contimeout);
    return new StandardSocketChannel(socketChannel, timeout);
}
 
Example 10
Source File: AdbHelper.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a port forwarding between a local and a remote port.
 * @param adbSockAddr the socket address to connect to adb
 * @param device the device on which to do the port forwarding
 * @param localPortSpec specification of the local port to forward, should be of format
 *                             tcp:<port number>
 * @param remotePortSpec specification of the remote port to forward to, one of:
 *                             tcp:<port>
 *                             localabstract:<unix domain socket name>
 *                             localreserved:<unix domain socket name>
 *                             localfilesystem:<unix domain socket name>
 *                             dev:<character device name>
 *                             jdwp:<process pid> (remote only)
 * @throws TimeoutException in case of timeout on the connection.
 * @throws AdbCommandRejectedException if adb rejects the command
 * @throws IOException in case of I/O error on the connection.
 */
public static void createForward(InetSocketAddress adbSockAddr, Device device,
        String localPortSpec, String remotePortSpec)
                throws TimeoutException, AdbCommandRejectedException, IOException {

    SocketChannel adbChan = null;
    try {
        adbChan = SocketChannel.open(adbSockAddr);
        adbChan.configureBlocking(false);

        byte[] request = formAdbRequest(String.format(
                "host-serial:%1$s:forward:%2$s;%3$s", //$NON-NLS-1$
                device.getSerialNumber(), localPortSpec, remotePortSpec));

        write(adbChan, request);

        AdbResponse resp = readAdbResponse(adbChan, false /* readDiagString */);
        if (!resp.okay) {
            Log.w("create-forward", "Error creating forward: " + resp.message);
            throw new AdbCommandRejectedException(resp.message);
        }
    } finally {
        if (adbChan != null) {
            adbChan.close();
        }
    }
}
 
Example 11
Source File: DriverOptions.java    From karate with MIT License 5 votes vote down vote up
private boolean waitForPort(String host, int port) {
    int attempts = 0;
    do {
        SocketAddress address = new InetSocketAddress(host, port);
        try {
            processLogger.debug("poll attempt #{} for port to be ready - {}:{}", attempts, host, port);
            SocketChannel sock = SocketChannel.open(address);
            sock.close();
            return true;
        } catch (IOException e) {
            sleep(pollInterval);
        }
    } while (attempts++ < pollAttempts);
    return false;
}
 
Example 12
Source File: SocketChannelDataLink.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 初期化処理, 受信用ワーカースレッド上で実行
 * @throws IOException
 */
protected synchronized void init() throws IOException {
	if (DEBUG) Log.v(TAG, "Client#init:");
	try {
		if (mChannel == null) {
			final InetSocketAddress address = new InetSocketAddress(mAddr, mPort);
			mChannel = SocketChannel.open(address);
		}
		setInit(true);
	} finally {
		notifyAll();
	}
	if (DEBUG) Log.v(TAG, "Client#init:finished");
}
 
Example 13
Source File: PlainHttpConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
PlainHttpConnection(InetSocketAddress addr, HttpClientImpl client) {
    super(addr, client);
    try {
        this.chan = SocketChannel.open();
        int bufsize = client.getReceiveBufferSize();
        chan.setOption(StandardSocketOptions.SO_RCVBUF, bufsize);
        chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
    } catch (IOException e) {
        throw new InternalError(e);
    }
}
 
Example 14
Source File: Initiator.java    From philadelphia with Apache License 2.0 5 votes vote down vote up
static Initiator open(SocketAddress address) throws IOException {
    SocketChannel channel = SocketChannel.open();

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.connect(address);
    channel.configureBlocking(false);

    return new Initiator(channel);
}
 
Example 15
Source File: TcpListener.java    From Mycat-Balance with Apache License 2.0 4 votes vote down vote up
@Override
public void run()
{
	synchronized (channelContext)
	{
		try
		{

			log.debug("start buildlink for {}", channelContext.getId());

			SocketChannel socketChannel = SocketChannel.open();
			
			
			// String xx = socketChannel.toString();
			bind(channelContext, socketChannel); // 绑定ip
			
	

			if (channelContext.getProxy() == null)
			{
				try
				{
					socketChannel.connect(socketAddress);
				} catch (IOException e)
				{
					log.error(
							channelContext.getBindIp() + ":" + channelContext.getBindPort() + "---"
									+ e.getLocalizedMessage(), e);
					socketChannel.close();
					throw e;
				}
				socketChannel.configureBlocking(false); // 非阻塞,此行不能少,否则IllegalBlockingModeException
			} else
			// 使用代理
			{
				socketChannel.connect(channelContext.getProxy().address());
				socketChannel.configureBlocking(false); // 非阻塞,此行不能少,否则IllegalBlockingModeException
				NioProxy.proxyImpl(socketChannel, socketAddress);
			}
			
			
			

			Socket socket = socketChannel.socket();
			socket.setSendBufferSize(1048576); // 262142
			socket.setReceiveBufferSize(1048576);

			channelContext.setMyIp(socketChannel.socket().getLocalAddress().getHostAddress());
			channelContext.setMyPort(socketChannel.socket().getLocalPort());
			channelContext.generateId();
			
			// int logIndex = 1;
			// log.warn("" + logIndex++);

			// CommunicateManager.getMapOfSocketChannelAndsocketChannelId().put(socketChannel,
			// channelContext.getsocketChannelId());
			mapOfSocketChannelAndChannelContext.put(socketChannel, channelContext);
			channelContext.setSocketChannel(socketChannel);
			channelContext.getStatVo().setStateTimeTcpBuilding(SystemTimer.currentTimeMillis());
			channelContext.setDesc4Err("");
			

			SendUtils.resumeCount(channelContext);

			socketChannel.register(socketMsgListener.selector, SelectionKey.OP_READ, socketMsgListener); // 注册到selector中去
			
			
			
			
			socketMsgListener.selector.wakeup();
			log.info("{} socket connection has been built, waiting app connection ", channelContext.getId());
			channelContext.setConnectionState(ConnectionState.TCP_ON);
			
			
			
			
		} catch (Exception t)
		{
			log.error("occured when build link " + channelContext.getId(), t);
			channelContext.getStatVo().getBuildExceptionTimes().incrementAndGet();
			channelContext.setConnectionState(ConnectionState.TCP_LINKFAILED);
			channelContext.setDesc4Err(t.getMessage());

		} finally
		{
			// skip it
		}
	}
	
}
 
Example 16
Source File: TestRELPSocketChannelHandler.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void run(List<String> messages) throws IOException, InterruptedException {
    final ByteBuffer buffer = ByteBuffer.allocate(1024);
    try {
        // starts the dispatcher listening on port 0 so it selects a random port
        dispatcher.open(null, 0, 4096);

        // starts a thread to run the dispatcher which will accept/read connections
        Thread dispatcherThread = new Thread(dispatcher);
        dispatcherThread.start();


        // create a client connection to the port the dispatcher is listening on
        final int realPort = dispatcher.getPort();
        try (SocketChannel channel = SocketChannel.open()) {
            channel.connect(new InetSocketAddress("localhost", realPort));
            Thread.sleep(100);

            // send the provided messages
            for (int i=0; i < messages.size(); i++) {
                buffer.clear();
                buffer.put(messages.get(i).getBytes(charset));
                buffer.flip();

                while (buffer.hasRemaining()) {
                    channel.write(buffer);
                }
                Thread.sleep(1);
            }
        }

        // wait up to 10 seconds to verify the responses
        long timeout = 10000;
        long startTime = System.currentTimeMillis();
        while (events.size() < messages.size() && (System.currentTimeMillis() - startTime < timeout)) {
            Thread.sleep(100);
        }

        // should have gotten an event for each message sent
        Assert.assertEquals(messages.size(), events.size());

    } finally {
        // stop the dispatcher thread and ensure we shut down handler threads
        dispatcher.close();
    }
}
 
Example 17
Source File: CassandraNodeConfTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() throws IOException {
    socketChannel = SocketChannel.open();
}
 
Example 18
Source File: Client.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected synchronized void reConnect() throws IOException {
    //0. Don't send connect request if it is connecting.
    if (isNotConnected()) {
        SocketAddress server = new InetSocketAddress(this.host, this.port);
        SelectableChannel channel = null;
        Session session2 = null;
        int event;

        if (this.udpMode) {
            //1. Create socket channel
            channel = DatagramChannel.open();
            channel.configureBlocking(false);

            //2. Create NioSession for each client connection
            session2 = new UDPSession(this.selectorManager);
            ((UDPSession) session2).setBufferSize(bufferSize);
            ((UDPSession) session2).setTarget(server);
            event = SelectionKey.OP_READ;
            session2.setStatus(SessionStatus.CLIENT_CONNECTED);
        } else {
            //1. Create socket channel
            channel = SocketChannel.open();
            channel.configureBlocking(false);
            try {
                if (this.tc != INVALID_TRAFFIC_CLASS_VALUE) ((SocketChannel) channel).socket().setTrafficClass(this.tc);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            ((SocketChannel) channel).connect(server);

            //2. Create NioSession for each client connection
            session2 = new TCPSession(this.selectorManager);
            ((TCPSession) session2).setTcpNoDelay(this.tcpNoDelay);
            event = SelectionKey.OP_CONNECT;
        }

        session2.setChannel(channel);
        session2.setKeepAlive(selectorManager.isKeepAlive());

        //3. Register event
        this.selectorManager.nextReactor().registerChannel(channel, event, session2);

        if (!this.udpMode) {
            //4. Wait to connect
            if (!session2.waitToConnect(this.connectTimeout)) {
                session2.asyncClose();
                throw new IOException("connect timed out to " + this.host + ":" + this.port);
            }

            //5. Handle exception
            if (session2.getStatus() == SessionStatus.NOT_CONNECTED) {
                session2.asyncClose();
                throw new IOException("connect failed to " + this.host + ":" + this.port);
            } else if (session2.getStatus() == SessionStatus.CLOSED) { //Already closed
                throw new IOException("connect failed to " + this.host + ":" + this.port); //Please see stderr.log for more details.
            }
        }

        this.session = session2;
    }
}
 
Example 19
Source File: SelectAfterRead.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] argv) throws Exception {

        // server: accept connection and write one byte
        try (ByteServer server = new ByteServer();
             SocketChannel sc = SocketChannel.open(server.address())) {

            server.acceptConnection();
            server.write(1);

            try (Selector sel = Selector.open()) {
                sc.read(ByteBuffer.allocate(1));
                sc.configureBlocking(false);
                sc.register(sel, SelectionKey.OP_READ);
                // previously on Windows select would select channel here, although there was
                // nothing to read
                if (sel.selectNow() != 0)
                    throw new Exception("Select returned nonzero value");
            }
        }

        // Now we will test a two reads combination
        // server: accept connection and write two bytes
        try (ByteServer server = new ByteServer();
             SocketChannel sc = SocketChannel.open(server.address())) {

            server.acceptConnection();
            server.write(2);

            try (Selector sel = Selector.open()) {
                sc.configureBlocking(false);
                sc.register(sel, SelectionKey.OP_READ);
                if (sel.select(TIMEOUT) != 1)
                    throw new Exception("One selected key expected");
                sel.selectedKeys().clear();
                // previously on Windows a channel would get selected only once
                if (sel.selectNow() != 1)
                    throw new Exception("One selected key expected");
                // Previously on Windows two consequent reads would cause select()
                // to select a channel, although there was nothing remaining to
                // read in the channel
                if (sc.read(ByteBuffer.allocate(1)) != 1)
                    throw new Exception("One byte expected");
                if (sc.read(ByteBuffer.allocate(1)) != 1)
                    throw new Exception("One byte expected");
                if (sel.selectNow() != 0)
                    throw new Exception("Select returned nonzero value");
            }
        }
    }
 
Example 20
Source File: ConnectionManager.java    From defense-solutions-proofs-of-concept with Apache License 2.0 4 votes vote down vote up
/**
 * Connect a Session to a server
 * 
 * @param session
 * @throws IOException
 */
void connect(Session session) throws IOException
{
	SocketChannel sChannel = SocketChannel.open();

	sChannel.configureBlocking(false);

	sChannel.connect(new InetSocketAddress(session.getRequestedConnection().getHostName(), session.getRequestedConnection().getPort()));

	sChannel.register(selector, sChannel.validOps());

	Connection con = new Connection(this, sChannel, session);
	session.setConnection(con);

	socChanMap.put(sChannel, session);
}