本文章爲做者原創,有問題的地方請提出指正。java
目前僅僅定義了2個方法,分別用來獲取本地或遠程服務器的地址。算法
package netty; import java.net.InetSocketAddress; /** * @author xfyou * @date 2019/8/28 */ public interface EndPoint { /** * Return the local Inet address * * @return The local Inet address to which this <code>EndPoint</code> is bound, or <code>null</code> * if this <code>EndPoint</code> does not represent a network connection. */ InetSocketAddress getLocalAddress(); /** * Return the remote Inet address * * @return The remote Inet address to which this <code>EndPoint</code> is bound, or <code>null</code> * if this <code>EndPoint</code> does not represent a network connection. */ InetSocketAddress getRemoteAddress(); }
主要是定義幾個抽象方法:apache
另外,提供了2個公共的方法給外部調用:bootstrap
內部私有的write()方法。write方法負責在connect成功後,把消息寫到遠程peer。翻閱源碼,咱們能夠看到以下的調用棧:服務器
package netty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import lombok.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.NotImplementedException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author xfyou * @date 2019/8/29 */ @Slf4j @RequiredArgsConstructor abstract class AbstractClient implements EndPoint { @NonNull private String hostName; @NonNull private int port; @NonNull @Getter(value = AccessLevel.PROTECTED) private int connectionTimeout; protected final CountDownLatch countDownLatch = new CountDownLatch(1); protected String respMsg; @SneakyThrows public void send(Object message) { doOpen(); doConnect(); write(message); } @SneakyThrows public String receive() { boolean b = countDownLatch.await(getConnectionTimeout(), TimeUnit.MILLISECONDS); if (!b) { log.error("Timeout(" + getConnectionTimeout() + "ms) when receiving response message"); } return respMsg; } private void write(Object message) { Channel channel = getChannel(); if (null != channel) { ChannelFuture f = channel.writeAndFlush(byteBufferFrom(message)).syncUninterruptibly(); if (!f.isSuccess()) { log.error("Failed to send message to " + getRemoteAddress() + f.cause().getMessage()); } } } private ByteBuf byteBufferFrom(Object message) { return message instanceof String ? Unpooled.copiedBuffer((String) message, StandardCharsets.UTF_8) : Unpooled.copiedBuffer((byte[]) message); } @Override public InetSocketAddress getRemoteAddress() { return new InetSocketAddress(hostName, port); } @Override public InetSocketAddress getLocalAddress() { throw new NotImplementedException("This method is not need to be implemented"); } /** * Open client. * * @throws Throwable */ protected abstract void doOpen() throws Throwable; /** * Connect to server. * * @throws Throwable */ protected abstract void doConnect() throws Throwable; /** * Get the connected channel. * * @return channel */ protected abstract Channel getChannel(); }
NettyClient類繼承了AbstractClient類,主要是實現了doOpen、doConnect、getChannel類;同時實現了一個自定義的ChannelHander用來在ChannelActive時獲取Channel以及有消息返回時讀取消息。異步
package netty; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import lombok.extern.slf4j.Slf4j; import java.nio.charset.StandardCharsets; /** * @author xfyou * @date 2019/8/28 */ @Slf4j public class NettyClient extends AbstractClient { private Bootstrap bootstrap; private volatile Channel channel; private static final NioEventLoopGroup NIO_GROUP = new NioEventLoopGroup(); public NettyClient(String hostName, int port, int connectionTimeout) { super(hostName, port, connectionTimeout); } private class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); channel = ctx.channel(); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { try { respMsg = msg.toString(StandardCharsets.UTF_8); } finally { countDownLatch.countDown(); ctx.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.error("An exception was thrown, cause:" + cause.getMessage()); ctx.close(); } } @Override protected void doOpen() throws Throwable { bootstrap = new Bootstrap(); bootstrap .group(NIO_GROUP) .remoteAddress(getRemoteAddress()) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectionTimeout()) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ClientHandler()); } }); } @Override public void doConnect() { ChannelFuture f = bootstrap.connect().syncUninterruptibly(); if (!f.isSuccess() && null != f.cause()) { log.error("The client failed to connect the server:" + getRemoteAddress() + ",error message is:" + f.cause().getMessage()); } } @Override protected Channel getChannel() { return channel; } }
package netty; import lombok.SneakyThrows; /** * Test * * @author xfyou */ public class Test { @SneakyThrows public static void main(String[] args) { NettyClient client = new NettyClient("127.0.0.1", 8080, 45000); client.send("aaa".getBytes()); // maybe do something else System.out.println(client.receive()); } }