public AioServerConnection(AsynchronousSocketChannel channel) { this.channel = channel; this.reader = new MsgReader(channel) { @Override protected void onMsg(Msg msg) { Command command = MsgConverter.convert(msg); Reply reply = commandHandler.handle(command); writer.write(reply.toMsg()); } }; this.writer = new MsgWriter(channel) { @Override protected void onWriteDone() { super.onWriteDone(); processCommand(); } }; }
/** *@description 接收客户端请求成功之后回调 *@time 创建时间:2017年7月20日上午11:05:16 *@param channel *@param serverHandler *@author dzn */ @Override public void completed(AsynchronousSocketChannel channel, AsyncTimeServerHandler serverHandler) { System.out.println("成功接收到客户端连接 : " + channel.toString()); //继续注册一个接收请求的处理类 serverHandler.asynchronousServerSocketChannel.accept(serverHandler, this); //创建一个数据缓冲区 ByteBuffer bb = ByteBuffer.allocate(1024); //去读取客户端发送的数据,并注册一个数据处理类 channel.read(bb, bb, new ReadCompletionHandler(channel)); }
@SuppressWarnings({"unchecked", "rawtypes"}) public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler, String schema) throws IOException { DBHostConfig dsc = pool.getConfig(); NetworkChannel channel = openSocketChannel(DbleServer.getInstance().isAIO()); MySQLConnection c = new MySQLConnection(channel, pool.isReadNode()); 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; }
/** * Creates a new client and adds it to the list of connections. * Sets the clients handler to the initial state of NameReader * * @param channel the newly accepted channel */ private void handleNewConnection(AsynchronousSocketChannel channel) { try { channel.setOption(StandardSocketOptions.TCP_NODELAY, true); } catch (IOException e) { // ignore // e.printStackTrace(); } //new dealer and channel AioServerDataDealer dealer = null; dealer = aioDataDealerFactory.getAioServerDataDealer(); int channelId = getChannelId(); AioServerChannel aioChannel = new AioServerChannel(channelId, channel, dealer, this); connections.put(channelId, aioChannel); //start channel aioChannel.run(null); }
/** * @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(); } }
private void retry() { try { TimeUnit.SECONDS.sleep(1); if (null != this.channel && this.channel.isOpen()) { this.channel.close(); } log.debug("连接:{}", this.socketAddress.toString()); final AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(this.group); asynchronousSocketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true); asynchronousSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); asynchronousSocketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); asynchronousSocketChannel.connect(this.socketAddress).get(5, TimeUnit.SECONDS); this.channel = new FastChannel(asynchronousSocketChannel, this.serializer, timeout); } catch (final Exception e) { retry(); } }
private CompletionHandler<AsynchronousSocketChannel, Integer> acceptCompletionHandler( int byteCount, AsynchronousServerSocketChannel socket) { return new CompletionHandler<AsynchronousSocketChannel, Integer>() { public void completed( AsynchronousSocketChannel ch, Integer acceptsToGo) { acceptsToGo = acceptsToGo-1; // System.out.println("server accepted, to go = " + acceptsToGo); writeStuffThreadAsync(socket, ch, byteCount, acceptsToGo); if (acceptsToGo > 0) { socket.accept(acceptsToGo, acceptCompletionHandler(byteCount, socket)); } } public void failed(Throwable exc, Integer attachment) { exc.printStackTrace(); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }; }
@Override public void completed(AsynchronousSocketChannel socketChannel, AioServerSocket serverSocket) { try { //接续接收 accept 请求 serverSocket.catchAccept(); AioSocket socket = new AioSocket(serverSocket,socketChannel); //触发 Accept 事件 EventTrigger.fireAcceptThread(socket.getSession()); } catch (IOException e) { EventTrigger.fireExceptionThread(null, e); } }
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException, TimeoutException { //打开 AsychronousServerSocketChannel 并将其绑定到类似于 ServerSocketChannel 的地址 //方法 bind() 将一个套接字地址作为其参数。找到空闲端口的便利方法是传递一个 null 地址,它会自动将套接字绑定到本地主机地址,并使用空闲的 临时 端口。 AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(null); //告诉通道接受一个连接 Future<AsynchronousSocketChannel> future = server.accept(); // 利用 Future 对象,当前线程可阻塞来等待结果: AsynchronousSocketChannel worker = future.get(); //超时 //AsynchronousSocketChannel worker = future.get(10, TimeUnit.SECONDS); //取消 // if (!future.isDone()) { // future.cancel(true);//cancel() 方法可利用一个布尔标志来指出执行接受的线程是否可被中断 // } // //// read a message from the client ByteBuffer readBuffer = ByteBuffer.allocate(1024); worker.read(readBuffer).get(10, TimeUnit.SECONDS); System.out.println("Message: " + new String(readBuffer.array())); }
public Nio2SSLSocket(AsynchronousSocketChannel sock, SSLContext sslc, boolean clientMode) { super(sock); this.engine = sslc.createSSLEngine(); this.engine.setUseClientMode(clientMode); String[] procols = { "TLSv1" }; this.engine.setEnabledProtocols(procols); int packetBufferSize = engine.getSession().getPacketBufferSize(); decodeBuf = ByteBuffer.allocateDirect(packetBufferSize); readBuf = ByteBuffer.allocateDirect(packetBufferSize); for (int i = 0; i < 2; i++) { writeBufs[i] = ByteBuffer.allocateDirect(packetBufferSize); writeBufs[i].limit(0); } writeBufs[0].clear(); }
private void connect() throws BindException{ String errorMessage = ""; if (socketChannel == null || !socketChannel.isOpen() || closed) { try { socketChannel = AsynchronousSocketChannel.open(); socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); socketChannel.connect(new InetSocketAddress(ip, port)).get(timeout, TimeUnit.MILLISECONDS); closed = false; //when connect to the server, keep receiving data either server response or server call receive(); } catch (Exception e) { log.error("Connection error: " + e.getMessage()); errorMessage = e.getMessage(); } } if (socketChannel == null) { throw new BindException(errorMessage); } }
private void connect() throws BindException{ String errorMessage = ""; if (socketChannel == null || !socketChannel.isOpen() || closed) { try { socketChannel = AsynchronousSocketChannel.open(); socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); socketChannel.connect(new InetSocketAddress(ip, port)).get(timeout, TimeUnit.MILLISECONDS); closed = false; log.debug("Session start to " + socketChannel.getRemoteAddress()); //when connect to the server, keep receiving data either server response or server call receive(); } catch (Exception e) { log.error("Connection error: " + e.getMessage()); errorMessage = e.getMessage(); } } if (socketChannel == null) { throw new BindException(errorMessage); } }
public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler) throws IOException { DBHostConfig dsc = pool.getConfig(); AsynchronousSocketChannel channel = openSocketChannel(); MySQLConnection c = new MySQLConnection(channel, pool.isReadNode()); c.setHost(dsc.getIp()); c.setPort(dsc.getPort()); c.setUser(dsc.getUser()); c.setPassword(dsc.getPassword()); // c.setSchema(dsc.getDatabase()); c.setHandler(new MySQLConnectionAuthenticator(c, handler)); c.setPool(pool); c.setIdleTimeout(pool.getConfig().getIdleTimeout()); channel.connect(new InetSocketAddress(dsc.getIp(), dsc.getPort()), c, MycatServer.getInstance().getConnector()); return c; }
public SocketSession(AsynchronousSocketChannel channel, ByteBuffer buffer, CodecFactory codecFactory) throws IOException { this.channel = channel; this.remoteAddress = channel.getRemoteAddress(); this.processor = new Processor(this); this.buffer = buffer; this.codec = codecFactory.getCodec(); this.describe = "local:" + channel.getLocalAddress() + " remote:" + remoteAddress + " hashCode/" + super.hashCode(); this.hashCode = super.hashCode(); attachment = new ConcurrentHashMap<Object, Object>(128); this.attachment.put(MSG_SURPLUS_LENGTH, -1); this.attachment.put(MSG_TMP, new byte[0]); this.remotePort = Integer.parseInt(this.toString().split(" ")[1] .split(":")[2]); }
/** * Construct a new {@code Client} * @param channel that this client listens on * @throws IOException If an I/O error occurs */ AbstractClient(AsynchronousSocketChannel channel) { super(); this.channel = channel; this.cipher = new Cryptographer(); /* * TODO This option was part of the ChatServer example by Oracle, but * should be used with caution: "The socket option should only be * enabled in cases where it is known that the coalescing impacts * performance". We need to figure out whether it is required to set * this option to true. * * try { * this.channel.setOption(StandardSocketOptions.TCP_NODELAY, true); * } catch (IOException e) { * e.printStackTrace(); * } * */ }
@SuppressWarnings("resource") 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); } }
@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); } }
public SocketClient(PoolManager pool_manager, InetSocketAddress server, Consumer<Node> callback_on_connection) throws IOException { if (pool_manager == null) { throw new NullPointerException("\"pool_manager\" can't to be null"); } this.distant_server_addr = server; if (server == null) { throw new NullPointerException("\"server\" can't to be null"); } this.callback_on_connection = callback_on_connection; if (callback_on_connection == null) { throw new NullPointerException("\"callback_on_connection\" can't to be null"); } handler_connect = new SocketConnect(); channel = AsynchronousSocketChannel.open(pool_manager.getChannelGroup()); channel.connect(server, new Node(this, pool_manager, channel), handler_connect); }
protected NetworkChannel openSocketChannel(boolean isAIO) throws IOException { if (isAIO) { return AsynchronousSocketChannel .open(MycatServer.getInstance().getNextAsyncChannelGroup()); } else { SocketChannel channel = null; channel = SocketChannel.open(); channel.configureBlocking(false); return channel; } }
@Override public void completed(AsynchronousSocketChannel result, Long id) { accept(result, id); // next pending waiting pendingAccept(); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public PostgreSQLBackendConnection make(PostgreSQLDataSource pool, ResponseHandler handler, final String schema) throws IOException { final DBHostConfig dsc = pool.getConfig(); NetworkChannel channel = this.openSocketChannel(MycatServer .getInstance().isAIO()); final PostgreSQLBackendConnection c = new PostgreSQLBackendConnection( channel, pool.isReadNode()); MycatServer.getInstance().getConfig().setSocketParams(c, false); // 设置NIOHandler c.setHandler(new PostgreSQLBackendConnectionHandler(c)); c.setHost(dsc.getIp()); c.setPort(dsc.getPort()); c.setUser(dsc.getUser()); c.setPassword(dsc.getPassword()); c.setSchema(schema); c.setPool(pool); c.setResponseHandler(handler); 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; }
@SuppressWarnings({ "unchecked", "rawtypes" }) // 这里传入的ResponseHandler为DelegateResponseHandler,在连接建立验证之后,会调用 public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler, String schema) throws IOException { // DBHost配置 DBHostConfig dsc = pool.getConfig(); // 根据是否为NIO返回SocketChannel或者AIO的AsynchronousSocketChannel NetworkChannel channel = openSocketChannel(MycatServer.getInstance() .isAIO()); // 新建MySQLConnection MySQLConnection c = new MySQLConnection(channel, pool.isReadNode()); // 根据配置初始化MySQLConnection 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); // 目前实际连接还未建立,handler为MySQL连接认证MySQLConnectionAuthenticatorHandler c.setHandler(new MySQLConnectionAuthenticatorHandler(c, handler)); c.setPool(pool); c.setIdleTimeout(pool.getConfig().getIdleTimeout()); // AIO和NIO连接方式建立实际的MySQL连接 if (channel instanceof AsynchronousSocketChannel) { ((AsynchronousSocketChannel) channel).connect( new InetSocketAddress(dsc.getIp(), dsc.getPort()), c, (CompletionHandler) MycatServer.getInstance() .getConnector()); } else { // 通过NIOConnector建立连接 // 通过NIOConnector建立实际连接的过程与前端连接的建立相似, // 也是先放在队列中,之后由NIOConnector去建立连接 ((NIOConnector) MycatServer.getInstance().getConnector()) .postConnect(c); } return c; }
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); }
private void cleanUpChannel(AsynchronousSocketChannel channel) { try { if (channel != null) { channel.close(); } } catch (Exception e){ // Ignore } }
public void testSingleConnect() throws IOException, ExecutionException, InterruptedException, TimeoutException { AsynchronousSocketChannel serverConnectionChannel = null; try { assertNotNull(serverAddress); serverConnectionChannel = AsynchronousSocketChannel.open(); serverConnectionChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); // Ensure we have have returned an open connection assertNotNull(serverConnectionChannel); assertTrue("Channel is not open", serverConnectionChannel.isOpen()); // Blocking connect Future<Void> future = serverConnectionChannel.connect(serverAddress); future.get(getTimeout(), TimeUnit.MILLISECONDS); // Ensure we are connected assertNotNull("Unable to get remote address", serverConnectionChannel.getRemoteAddress()); } finally { if (serverConnectionChannel != null) { try { serverConnectionChannel.close(); } catch (ClosedChannelException cce) { // That's ok } assertFalse("Channel was not closed", serverConnectionChannel.isOpen()); } } }
private void handle(final AsynchronousSocketChannel channel) { requests.offer(executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { synchronized (output) { try (InputStream input = Channels.newInputStream(channel)) { ByteStreams.copy(input, output); } catch (IOException e) { throw new RuntimeException("Error processing user request", e); } } return null; } })); }
public AsyncTimeClientHandler(String host, int port) { this.port = port; this.host = host; try{ this.asynchronousSocketChannel = AsynchronousSocketChannel.open(); }catch(Exception e){ e.printStackTrace(); } }
@Override public void completed(AsynchronousSocketChannel channel, AsyncServerHandler serverHandler) { // 继续接受其他客户端的请求 Server.clientCount++; System.out.println("连接的客户端数:" + Server.clientCount); serverHandler.channel.accept(serverHandler, this); // 创建新的Buffer ByteBuffer buffer = ByteBuffer.allocate(1024); // 异步读 第三个参数为接收消息回调的业务Handler channel.read(buffer, buffer, new ReadHandler(channel)); }
public AsyncClientHandler(String host, int port) { this.host = host; this.port = port; try { // 创建异步的客户端通道 clientChannel = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } }
protected NetworkChannel openSocketChannel(boolean isAIO) throws IOException { if (isAIO) { return AsynchronousSocketChannel.open(DbleServer.getInstance().getNextAsyncChannelGroup()); } else { SocketChannel channel = null; channel = SocketChannel.open(); channel.configureBlocking(false); return channel; } }
public AioServerChannel(int channelId, AsynchronousSocketChannel channel, AioServerDataDealer dealer, AioServer aioServer) { dealer.serverOnConnect(this); this.channel = channel; this.dealer = dealer; this.aioServer = aioServer; this.channelId = channelId; }
public AsynchronousSocketChannel connect(SocketAddress remote, AioClientDataDealer aioClientDataDealer) throws IOException { AsynchronousSocketChannel listener = createListener(channelGroup); //log.log(1, "client start connect"); AcceptHandler acceptHandler = new AcceptHandler(listener, aioClientDataDealer); listener.connect(remote, null, acceptHandler); return listener; }
@Override public void run() { System.out.println(Thread.currentThread().getName() + "---run"); InetSocketAddress r = new InetSocketAddress("10.213.33.176", 11200); try { AsynchronousSocketChannel channel = connect(r); System.out.println(channel); } catch (IOException e) { e.printStackTrace(); } }