socketChannel.connect(serverAddress, null, new CompletionHandler<Void, Void>() {
@SuppressWarnings("deprecation") private void initializeSocketChannel(final AsyncCompletionHandler<Void> handler, final Queue<SocketAddress> socketAddressQueue) { if (socketAddressQueue.isEmpty()) { handler.failed(new MongoSocketException("Exception opening socket", serverAddress)); } else { SocketAddress socketAddress = socketAddressQueue.poll(); try { AsynchronousSocketChannel attemptConnectionChannel = AsynchronousSocketChannel.open(group); attemptConnectionChannel.setOption(StandardSocketOptions.TCP_NODELAY, true); attemptConnectionChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getReceiveBufferSize() > 0) { attemptConnectionChannel.setOption(StandardSocketOptions.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { attemptConnectionChannel.setOption(StandardSocketOptions.SO_SNDBUF, settings.getSendBufferSize()); } attemptConnectionChannel.connect(socketAddress, null, new OpenCompletionHandler(handler, socketAddressQueue, attemptConnectionChannel)); } catch (IOException e) { handler.failed(new MongoSocketOpenException("Exception opening socket", serverAddress, e)); } catch (Throwable t) { handler.failed(t); } } }
//Create an Asynchronous channel. No connection has actually been established yet AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(); /**Connect to an actual server on the given port and address. The operation returns a type of Future, the basis of the all asynchronous operations in java. In this case, a Void is returned because nothing is returned after a successful socket connection */ Void connect = asynchronousSocketChannel.connect(new InetSocketAddress("127.0.0.1", 5000)).get(); //Allocate data structures to use to communicate over the wire ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes()); //Send the message Future<Integer> successfullyWritten= asynchronousSocketChannel.write(helloBuffer); //Do some stuff here. The point here is that asynchronousSocketChannel.write() //returns almost immediately, not waiting to actually finish writing //the hello to the channel before returning control to the currently executing thread doSomethingElse(); //now you can come back and check if it was all written (or not) System.out.println("Bytes written "+successfullyWritten.get());
@Override protected void requestAsync(Fiber current, CompletionHandler<Void, Fiber> completionHandler) { ac.connect(remote, current, completionHandler); } }.run();
void open() { sock.connect(remote, this, new CompletionHandler<Void, Nio2SocketBase>() { @Override public void completed(Void result, Nio2SocketBase attachment) { handler.opened(Nio2SocketBase.this); _read(); } @Override public void failed(Throwable exc, Nio2SocketBase attachment) { handler.error(exc, Nio2SocketBase.this); } }); }
@Override protected void requestAsync() { ac.connect(remote, null, makeCallback()); } }.run();
@Override protected void requestAsync() { ac.connect(remote, null, makeCallback()); } }.run(timeout, timeUnit);
/** * Starts connection to a server. IO requests can be queued immediately, * but will be executed only after connection completes. * * @param name name of the connection * @param addr address of the server to connect * @throws IOException exception thrown by {@link AsynchronousSocketChannel#open} */ public ClientConnection(String name, SocketAddress addr) throws IOException { super(name); AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(); channel.connect(addr, channel, this); }
@Override public void run() { latch = new CountDownLatch(1); client.connect(new InetSocketAddress(host, port), this, this); try { latch.await(); } catch (InterruptedException e1) { e1.printStackTrace(); } try { client.close(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void run() { latch = new CountDownLatch(1); /** * 发起异步操作 * @param attachment AsynchronousSocketChannel的附件,用于回调通知时作为入参被传递,调用者可以自定义 * @param handler 异步操作回调通知接口,由调用者实现 */ client.connect(new InetSocketAddress(host, port), this, this); try{ latch.await(); }catch(InterruptedException e1){ e1.printStackTrace(); } try{ client.close(); }catch(IOException e){ e.printStackTrace(); } }
@Override public void connect(InetSocketAddress remoteAddress) throws IOException { String remoteHostname = remoteAddress.getHostString(); try { Future<Void> connectFuture = socketChannel.connect(remoteAddress); connectFuture.get(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); connected.set(true); } catch (ExecutionException | TimeoutException e) { throw TransportException.Wrapper.wrap(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw TransportException.Wrapper.wrap(e); } packetReader.start(remoteHostname, this.soTimeout); }
@Override public void connect(InetSocketAddress remoteAddress) throws IOException { String remoteHostname = remoteAddress.getHostString(); try { Future<Void> connectFuture = socketChannel.connect(remoteAddress); connectFuture.get(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); connected.set(true); } catch (ExecutionException | TimeoutException e) { throw TransportException.Wrapper.wrap(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw TransportException.Wrapper.wrap(e); } packetReader.start(remoteHostname, this.soTimeout); }
void ready() { try { channel = AsynchronousSocketChannel.open(); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); Future<Void> future = channel.connect(remote.getAddress()); if (future.get() != null) { log.log(Level.WARNING, "Can't connect to {0}", remote); } else { log.log(Level.INFO, "Connected to server {0}", remote); } } catch (Exception e) { e.printStackTrace(); } }
InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName("10.1.1.98"), 1236); AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open(); clientSocketChannel.connect(hostAddress).get(); ByteBuffer buffer = getBuffer(); clientSocketChannel.read(buffer, Void, new ReadHandler(buffer));
/** * aio模式发送数据 * @param host 服务器主机 * @param port 服务器端口 * @param data 发送数据 */ public static void asyn(String host, int port, byte[] data) { // 实例化Socket try (AsynchronousSocketChannel socket = AsynchronousSocketChannel.open()) { // 连接服务器 socket.connect(new InetSocketAddress(host, port)).get(); // 写入数据流 socket.write(ByteBuffer.wrap(data)).get(); } catch (Exception e) { Logs.error(e); } }
public DirectHttpConnection(MappedHttpConnectionFactory factory, AsynchronousSocketChannel sourceChannel, HostPort socketAddress) throws IOException { super(sourceChannel); HttpUtils.getFuture(channel.connect(new InetSocketAddress(socketAddress.getHost(), socketAddress.getPort()))); prepareChannel(factory, sourceChannel, socketAddress); }
public NtlmProxyHttpConnection(MappedHttpConnectionFactory factory, AsynchronousSocketChannel sourceChannel, String host, int port, String domain, String username, String password, HttpRequestManipulator manipulator) throws IOException { super(sourceChannel); this.factory = factory; this.socketAddress = new HostPort(host, port); this.domain = domain; this.username = username; this.password = password; this.manipulator = manipulator; LOG.finest("Trying to connect to " + socketAddress.toString()); HttpUtils.getFuture(channel.connect(new InetSocketAddress(socketAddress.getHost(), socketAddress.getPort()))); if (LOG.isLoggable(Level.INFO)) { LOG.log(Level.INFO, "Connected thread {0} to port {1}", new Object[] { Thread.currentThread().getName(), channel.getLocalAddress().toString() }); } tentativeHandler = new TentativeHandler(sourceChannel); }
@Override public synchronized CompletableFuture<RaftResponseMessage> send(final RaftRequestMessage request) { this.logger.debug(String.format("trying to send message %s to server %d at endpoint %s", request.getMessageType().toString(), request.getDestination(), this.remote.toString())); CompletableFuture<RaftResponseMessage> result = new CompletableFuture<RaftResponseMessage>(); if(this.connection == null || !this.connection.isOpen()){ try{ this.connection = AsynchronousSocketChannel.open(this.channelGroup); this.connection.connect(this.remote, new AsyncTask<RaftRequestMessage>(request, result), handlerFrom((Void v, AsyncTask<RaftRequestMessage> task) -> { sendAndRead(task, false); })); }catch(Throwable error){ closeSocket(); result.completeExceptionally(error); } }else{ this.sendAndRead(new AsyncTask<RaftRequestMessage>(request, result), false); } return result; }
/** * @param asynchronousChannelGroup * @throws IOException * @throws ExecutionException * @throws InterruptedException */ @Override public AioSession<T> start(AsynchronousChannelGroup asynchronousChannelGroup) throws IOException, ExecutionException, InterruptedException { //启动SSL服务 sslConfig.setClientMode(true); sslService = new SSLService(sslConfig); AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open(asynchronousChannelGroup); socketChannel.connect(new InetSocketAddress(config.getHost(), config.getPort())).get(); //连接成功则构造AIOSession对象 session = new SSLAioSession<T>(socketChannel, config, new ReadCompletionHandler<T>(), new WriteCompletionHandler<T>(), sslService); session.initSession(); return session; }
@Override public IoConnectFuture connect(SocketAddress address) { IoConnectFuture future = new DefaultIoConnectFuture(null); try { AsynchronousChannelGroup group = getChannelGroup(); AsynchronousSocketChannel socket = setSocketOptions(openAsynchronousSocketChannel(address, group)); Nio2CompletionHandler<Void, Object> completionHandler = ValidateUtils.checkNotNull(createConnectionCompletionHandler(future, socket, getFactoryManager(), getIoHandler()), "No connection completion handler created for %s", address); socket.connect(address, null, completionHandler); } catch (Throwable exc) { Throwable t = GenericUtils.peelException(exc); future.setException(t); } return future; }