java.nio.channels.AsynchronousSocketChannel Java Examples
The following examples show how to use
java.nio.channels.AsynchronousSocketChannel.
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: ChannelContext.java From t-io with Apache License 2.0 | 6 votes |
/** * * @param tioConfig * @param asynchronousSocketChannel * @author tanyaowu */ public ChannelContext(TioConfig tioConfig, AsynchronousSocketChannel asynchronousSocketChannel) { super(); init(tioConfig, asynchronousSocketChannel); if (tioConfig.sslConfig != null) { try { SslFacadeContext sslFacadeContext = new SslFacadeContext(this); if (tioConfig.isServer()) { sslFacadeContext.beginHandshake(); } } catch (Exception e) { log.error("在开始SSL握手时发生了异常", e); Tio.close(this, "在开始SSL握手时发生了异常" + e.getMessage(), CloseCode.SSL_ERROR_ON_HANDSHAKE); return; } } }
Example #2
Source File: DefaultGLSPServerLauncher.java From graphical-lsp with Eclipse Public License 2.0 | 6 votes |
private void createClientConnection(AsynchronousSocketChannel socketChannel) { Injector injector = Guice.createInjector(getGLSPModule()); GsonConfigurator gsonConf = injector.getInstance(GsonConfigurator.class); InputStream in = Channels.newInputStream(socketChannel); OutputStream out = Channels.newOutputStream(socketChannel); Consumer<GsonBuilder> configureGson = (GsonBuilder builder) -> gsonConf.configureGsonBuilder(builder); Function<MessageConsumer, MessageConsumer> wrapper = Function.identity(); GLSPServer languageServer = injector.getInstance(GLSPServer.class); Launcher<GLSPClient> launcher = Launcher.createIoLauncher(languageServer, GLSPClient.class, in, out, threadPool, wrapper, configureGson); languageServer.connect(launcher.getRemoteProxy()); launcher.startListening(); try { SocketAddress remoteAddress = socketChannel.getRemoteAddress(); log.info("Started language server for client " + remoteAddress); } catch (IOException ex) { log.error("Failed to get the remoteAddress for the new client connection: " + ex.getMessage(), ex); } }
Example #3
Source File: AsyncSocketFactory.java From lams with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public <T extends Closeable> T connect(String host, int port, Properties props, int loginTimeout) throws IOException { try { this.channel = AsynchronousSocketChannel.open(); //channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true); this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024); this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024); Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port)); connectPromise.get(); } catch (CJCommunicationsException e) { throw e; } catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) { throw new CJCommunicationsException(ex); } return (T) this.channel; }
Example #4
Source File: ChannelContext.java From t-io with Apache License 2.0 | 6 votes |
/** * @param asynchronousSocketChannel the asynchronousSocketChannel to set */ public void setAsynchronousSocketChannel(AsynchronousSocketChannel asynchronousSocketChannel) { this.asynchronousSocketChannel = asynchronousSocketChannel; if (asynchronousSocketChannel != null) { try { Node clientNode = createClientNode(asynchronousSocketChannel); setClientNode(clientNode); } catch (IOException e) { log.info(e.toString(), e); assignAnUnknownClientNode(); } } else { assignAnUnknownClientNode(); } }
Example #5
Source File: AsynchronousSocketStep.java From coroutines with Apache License 2.0 | 6 votes |
/*************************************** * {@inheritDoc} */ @Override protected ByteBuffer execute( ByteBuffer rData, Continuation<?> rContinuation) { try { AsynchronousSocketChannel rChannel = getSocketChannel(rContinuation); if (rChannel.getRemoteAddress() == null) { rChannel.connect(getSocketAddress(rContinuation)).get(); } performBlockingOperation(rChannel, rData); } catch (Exception e) { throw new CoroutineException(e); } return rData; }
Example #6
Source File: AsynchronousSocketStep.java From coroutines with Apache License 2.0 | 6 votes |
/*************************************** * Returns the channel to be used by this step. This first checks the * currently exexcuting coroutine in the continuation parameter for an * existing {@link #SOCKET_CHANNEL} relation. If that doesn't exists or the * channel is closed a new {@link AsynchronousSocketChannel} will be opened * and stored in the coroutine relation. Using the coroutine to store the * channel allows coroutines to be structured so that multiple subroutines * perform communication on different channels. * * @param rContinuation The continuation to query for an existing channel * * @return The socket channel * * @throws IOException If opening the channel fails */ protected AsynchronousSocketChannel getSocketChannel( Continuation<?> rContinuation) throws IOException { Coroutine<?, ?> rCoroutine = rContinuation.getCurrentCoroutine(); AsynchronousSocketChannel rChannel = rCoroutine.get(SOCKET_CHANNEL); if (rChannel == null || !rChannel.isOpen()) { rChannel = AsynchronousSocketChannel.open(getChannelGroup(rContinuation)); rCoroutine.set(SOCKET_CHANNEL, rChannel).annotate(MANAGED); } return rChannel; }
Example #7
Source File: ChannelContext.java From talent-aio with GNU Lesser General Public License v2.1 | 6 votes |
/** * @param asynchronousSocketChannel the asynchronousSocketChannel to set */ public void setAsynchronousSocketChannel(AsynchronousSocketChannel asynchronousSocketChannel) { this.asynchronousSocketChannel = asynchronousSocketChannel; if (asynchronousSocketChannel != null) { try { Node clientNode = createClientNode(asynchronousSocketChannel); setClientNode(clientNode); } catch (IOException e) { log.info(e.toString(), e); assignAnUnknownClientNode(); } } else { assignAnUnknownClientNode(); } }
Example #8
Source File: AsyncSocketFactory.java From FoxTelem with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public <T extends Closeable> T connect(String host, int port, PropertySet props, int loginTimeout) throws IOException { try { this.channel = AsynchronousSocketChannel.open(); //channel.setOption(java.net.StandardSocketOptions.TCP_NODELAY, true); this.channel.setOption(java.net.StandardSocketOptions.SO_SNDBUF, 128 * 1024); this.channel.setOption(java.net.StandardSocketOptions.SO_RCVBUF, 128 * 1024); Future<Void> connectPromise = this.channel.connect(new InetSocketAddress(host, port)); connectPromise.get(); } catch (CJCommunicationsException e) { throw e; } catch (IOException | InterruptedException | ExecutionException | RuntimeException ex) { throw new CJCommunicationsException(ex); } return (T) this.channel; }
Example #9
Source File: TcpManager.java From jane with GNU Lesser General Public License v3.0 | 6 votes |
public void startClient(SocketAddress addr, Object attachment, AsynchronousChannelGroup group) { AsynchronousSocketChannel channel = null; try { channel = AsynchronousSocketChannel.open(group); int recvBufSize = onChannelCreated(channel, attachment); if (recvBufSize >= 0) channel.connect(addr, new ConnectParam(channel, recvBufSize), _connectHandler); else channel.close(); } catch (Throwable e) { doException(null, e); closeChannel(channel); } }
Example #10
Source File: ZKMetricUpdater.java From vespa with Apache License 2.0 | 6 votes |
private Optional<String> retrieveReport() { try (AsynchronousSocketChannel chan = AsynchronousSocketChannel.open()) { InetSocketAddress zkAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), zkPort); Future<Void> connected = chan.connect(zkAddress); connected.get(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); Future<Integer> written = chan.write(ByteBuffer.wrap("mntr\n".getBytes(StandardCharsets.UTF_8))); written.get(WRITE_TIMEOUT_MS, TimeUnit.MILLISECONDS); int nread = -1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteBuffer buffer = ByteBuffer.allocate(4096); do { Future<Integer> read = chan.read(buffer); nread = read.get(READ_TIMEOUT_MS, TimeUnit.MILLISECONDS); buffer.flip(); baos.write(buffer.array()); buffer.clear(); } while (nread >= 0); return Optional.of(baos.toString(StandardCharsets.UTF_8)); } catch (IOException | InterruptedException | ExecutionException | TimeoutException e) { log.warning("Failure in retrieving monitoring data: (" + e.getClass().getName() + ") " + e.getMessage()); return Optional.empty(); } }
Example #11
Source File: CompletionHandlerRelease.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
@Test public void testConnect() throws Exception { try (Server server = new Server()) { try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(GROUP)) { CountDownLatch latch = new CountDownLatch(1); Handler<Void,Object> handler = new Handler<Void,Object>("connect", latch); ReferenceQueue queue = new ReferenceQueue<WeakReference>(); WeakReference<Object> ref = new WeakReference<Object>(handler, queue); ch.connect(server.address(), null, handler); try { latch.await(); } catch (InterruptedException ignore) { } handler = null; waitForRefToClear(ref, queue); server.accept().get().close(); } } }
Example #12
Source File: TcpManager.java From jane with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void failed(Throwable ex, ConnectParam param) { AsynchronousSocketChannel channel = param.channel; try { SocketAddress addr = (channel.isOpen() ? channel.getRemoteAddress() : null); closeChannel(channel); onConnectFailed(addr, ex); } catch (Exception e) { closeChannel(channel); doException(null, e); } }
Example #13
Source File: CompletionHandlerRelease.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
@Test public void testConnect() throws Exception { try (Server server = new Server()) { try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(GROUP)) { CountDownLatch latch = new CountDownLatch(1); Handler<Void,Object> handler = new Handler<Void,Object>("connect", latch); ReferenceQueue queue = new ReferenceQueue<WeakReference>(); WeakReference<Object> ref = new WeakReference<Object>(handler, queue); ch.connect(server.address(), null, handler); try { latch.await(); } catch (InterruptedException ignore) { } handler = null; waitForRefToClear(ref, queue); server.accept().get().close(); } } }
Example #14
Source File: MySQLConnectionFactory.java From dble with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings({"unchecked", "rawtypes"}) public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler, String schema) throws IOException { DataSourceConfig dsc = pool.getConfig(); NetworkChannel channel = openSocketChannel(DbleServer.getInstance().isAIO()); MySQLConnection c = new MySQLConnection(channel, pool.isReadNode(), pool.isAutocommitSynced(), pool.isIsolationSynced()); c.setSocketParams(false); c.setHost(dsc.getIp()); c.setPort(dsc.getPort()); c.setUser(dsc.getUser()); c.setPassword(dsc.getPassword()); c.setSchema(schema); c.setHandler(new MySQLConnectionAuthenticator(c, handler)); c.setPool(pool); c.setIdleTimeout(pool.getConfig().getIdleTimeout()); if (channel instanceof AsynchronousSocketChannel) { ((AsynchronousSocketChannel) channel).connect( new InetSocketAddress(dsc.getIp(), dsc.getPort()), c, (CompletionHandler) DbleServer.getInstance().getConnector()); } else { ((NIOConnector) DbleServer.getInstance().getConnector()).postConnect(c); } return c; }
Example #15
Source File: CompletionHandlerRelease.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Test public void testRead() throws Exception { try (Server server = new Server(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(GROUP)) { ch.connect(server.address()).get(); try (AsynchronousSocketChannel sc = server.accept().get()) { ByteBuffer src = ByteBuffer.wrap("hello".getBytes("UTF-8")); sc.setOption(SO_SNDBUF, src.remaining()); sc.write(src).get(); CountDownLatch latch = new CountDownLatch(1); Handler<Integer,Object> handler = new Handler<Integer,Object>("read", latch); ReferenceQueue queue = new ReferenceQueue<WeakReference>(); WeakReference<Object> ref = new WeakReference<Object>(handler, queue); ByteBuffer dst = ByteBuffer.allocate(64); ch.read(dst, null, handler); try { latch.await(); } catch (InterruptedException ignore) { } handler = null; waitForRefToClear(ref, queue); } } }
Example #16
Source File: MySQLConnectionFactory.java From Mycat2 with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler, String schema) throws IOException { DBHostConfig dsc = pool.getConfig(); NetworkChannel channel = openSocketChannel(MycatServer.getInstance() .isAIO()); MySQLConnection c = new MySQLConnection(channel, pool.isReadNode()); MycatServer.getInstance().getConfig().setSocketParams(c, false); c.setHost(dsc.getIp()); c.setPort(dsc.getPort()); c.setUser(dsc.getUser()); c.setPassword(dsc.getPassword()); c.setSchema(schema); c.setHandler(new MySQLConnectionAuthenticator(c, handler)); c.setPool(pool); c.setIdleTimeout(pool.getConfig().getIdleTimeout()); if (channel instanceof AsynchronousSocketChannel) { ((AsynchronousSocketChannel) channel).connect( new InetSocketAddress(dsc.getIp(), dsc.getPort()), c, (CompletionHandler) MycatServer.getInstance() .getConnector()); } else { ((NIOConnector) MycatServer.getInstance().getConnector()) .postConnect(c); } return c; }
Example #17
Source File: AioHelperImpl.java From tephra with MIT License | 5 votes |
@Override public String put(AsynchronousSocketChannel socketChannel) { String sessionId = getSessionId(socketChannel); map.put(sessionId, socketChannel); return sessionId; }
Example #18
Source File: NetworkUtil.java From Tatala-RPC with Apache License 2.0 | 5 votes |
public static long getClientIdBySocketChannel(AsynchronousSocketChannel socketChannel) throws IOException{ InetSocketAddress address = (InetSocketAddress)socketChannel.getRemoteAddress(); byte[] quad = address.getAddress().getAddress(); int port = address.getPort(); long clientId = NetworkUtil.convertIpPortToUniqueId(quad, port); return clientId; }
Example #19
Source File: HsmsSsCommunicator.java From secs4java8 with Apache License 2.0 | 5 votes |
protected boolean addChannel(AsynchronousSocketChannel ch) { synchronized ( channels ) { if ( channels.isEmpty() ) { return channels.add(ch); } else { return false; } } }
Example #20
Source File: ChannelContext.java From talent-aio with GNU Lesser General Public License v2.1 | 5 votes |
/** * @param groupContext * @param asynchronousSocketChannel * * @author: tanyaowu * @创建时间: 2016年11月16日 下午1:13:56 * */ public ChannelContext(GroupContext<SessionContext, P, R> groupContext, AsynchronousSocketChannel asynchronousSocketChannel) { super(); this.setGroupContext(groupContext); this.setAsynchronousSocketChannel(asynchronousSocketChannel); this.readCompletionHandler = new ReadCompletionHandler<>(this); this.writeCompletionHandler = new WriteCompletionHandler<>(this); }
Example #21
Source File: TcpManager.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
/** * 连接创建且在TcpSession创建前响应一次. 可以修改一些连接的设置 * @param channel * @param attachment 作为客户端建立的连接时为startClient传入的参数; 作为服务器建立的连接时为null * @return 返回>=0表示读缓冲区大小(每次最多读的字节数,0表示取默认值);返回<0表示断开连接,不再创建TcpSession */ @SuppressWarnings("static-method") public int onChannelCreated(AsynchronousSocketChannel channel, Object attachment) throws IOException { channel.setOption(StandardSocketOptions.TCP_NODELAY, false); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, false); channel.setOption(StandardSocketOptions.SO_RCVBUF, TcpSession.DEF_RECV_SOBUF_SIZE); channel.setOption(StandardSocketOptions.SO_SNDBUF, TcpSession.DEF_SEND_SOBUF_SIZE); // channel.setOption(StandardSocketOptions.SO_LINGER, -1); // AIO目前不支持设置linger,而且固定为0,因此直接close会导致发RST,最好先shutdownOutput再close return 0; }
Example #22
Source File: SocketReceive.java From coroutines with Apache License 2.0 | 5 votes |
/*************************************** * {@inheritDoc} */ @Override protected boolean performAsyncOperation( int nBytesReceived, AsynchronousSocketChannel rChannel, ByteBuffer rData, ChannelCallback<Integer, AsynchronousSocketChannel> rCallback) throws IOException { boolean bFinished = false; if (nBytesReceived >= 0) { bFinished = pCheckFinished.test(nBytesReceived, rData); } if (nBytesReceived != -1 && !bFinished && rData.hasRemaining()) { rChannel.read(rData, rData, rCallback); } else { checkErrors(rData, nBytesReceived, bFinished); rData.flip(); } return bFinished; }
Example #23
Source File: TestProxy.java From qpid-jms with Apache License 2.0 | 5 votes |
private void shutdownOutput(AsynchronousSocketChannel channel) { if (channel != null && channel.isOpen()) { try { LOG.info("shutdown output for ({})", channel); channel.shutdownOutput(); } catch (IOException e) { LOG.error("cannot shutdown output to ({})", channel, e); } } }
Example #24
Source File: TestEchoAio.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
@Override public int onChannelCreated(AsynchronousSocketChannel channel, Object attachment) throws IOException { super.onChannelCreated(channel, attachment); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); return 0; }
Example #25
Source File: AsyncTimeClientHandler.java From JavaInterview with Apache License 2.0 | 5 votes |
public AsyncTimeClientHandler(String host, int port) { this.host = host; this.port = port; try { this.timeClient = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } }
Example #26
Source File: NioBridge.java From java-async-util with Apache License 2.0 | 5 votes |
static CompletionStage<AsynchronousSocketChannel> connect(final SocketAddress addr) { try { final AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(); return connect(channel, addr).thenApply(ig -> channel); } catch (final IOException e) { return StageSupport.exceptionalStage(e); } }
Example #27
Source File: AsyncChannelWrapperSecure.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
public AsyncChannelWrapperSecure(AsynchronousSocketChannel socketChannel, SSLEngine sslEngine) { this.socketChannel = socketChannel; this.sslEngine = sslEngine; int socketBufferSize = sslEngine.getSession().getPacketBufferSize(); socketReadBuffer = ByteBuffer.allocateDirect(socketBufferSize); socketWriteBuffer = ByteBuffer.allocateDirect(socketBufferSize); }
Example #28
Source File: CompletionHandlerRelease.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
@Test public void testWrite() throws Exception { try (Server server = new Server(); AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(GROUP)) { ch.connect(server.address()).get(); try (AsynchronousSocketChannel sc = server.accept().get()) { ByteBuffer src = ByteBuffer.wrap("hello".getBytes("UTF-8")); sc.setOption(SO_SNDBUF, src.remaining()); CountDownLatch latch = new CountDownLatch(1); Handler<Integer,Object> handler = new Handler<Integer,Object>("write", latch); ReferenceQueue queue = new ReferenceQueue<WeakReference>(); WeakReference<Object> ref = new WeakReference<Object>(handler, queue); sc.write(src, null, handler); try { latch.await(); } catch (InterruptedException ignore) { } handler = null; waitForRefToClear(ref, queue); } } }
Example #29
Source File: MultiProducerIteration.java From java-async-util with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws IOException { final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(null); final SocketAddress addr = server.getLocalAddress(); // on the client side, concurrently connect to addr 4 times, and write 100 random integers on // each connection final CompletionStage<Void> writeStage = Combinators.allOf(IntStream .range(0, 4) .mapToObj(i -> connect(addr) .thenComposeAsync(channel -> Iteration.write100Randoms(channel))) .collect(Collectors.toList())) .thenApply(ig -> null); // on the server side, we'd like to accept 4 connections and route their messages into a single // place we can consume final AsyncIterator<AsynchronousSocketChannel> clientConnections = AsyncIterator // listen for next connection .generate(() -> accept(server)) // only will take 4 connections .take(4); final AsyncIterator<Integer> results = routeClientMessages(clientConnections); // do something with the results! - print each result as it comes from each client final CompletionStage<Void> printStage = results.forEach(i -> System.out.println(i)); // wait for both the clients and the server/printing to complete writeStage.thenAcceptBoth(printStage, (ig1, ig2) -> { System.out.println("completed successfully"); }); }
Example #30
Source File: SslAsynchronousSocketChannel.java From smart-socket with Apache License 2.0 | 5 votes |
public SslAsynchronousSocketChannel(AsynchronousSocketChannel asynchronousSocketChannel, SslService sslService, BufferPage bufferPage) { super(null); this.handshakeModel = sslService.createSSLEngine(asynchronousSocketChannel, bufferPage); this.sslService = sslService; this.asynchronousSocketChannel = asynchronousSocketChannel; this.sslEngine = handshakeModel.getSslEngine(); this.netWriteBuffer = handshakeModel.getNetWriteBuffer(); this.netReadBuffer = handshakeModel.getNetReadBuffer(); this.appReadBuffer = handshakeModel.getAppReadBuffer(); }