前几天用Netty写了一个简单的服务端,点击进入Netty服务端,今天把相应的客户端实现一下。
上次忘了贴出maven依赖了,这次补上
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>
代码一览
- 客户端启动入口
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import java.net.URI;
import java.net.URISyntaxException;
/**
* @ClassName : NettyClient
* @Description : netty客户端
* @Author : 明心
* @Date: 2021-01-23
*/
public class NettyClient {
public static void main(String[] args) {
final NetClientHandler netClientHandler = new NetClientHandler();
EventLoopGroup group=new NioEventLoopGroup();
Bootstrap client=new Bootstrap();
client.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE,true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//包含编码器和解码器:
// pipeline.addLast(new HttpClientCodec())等价于new HttpRequestEncoder() + new HttpResponseDecoder()
//request编码
pipeline.addLast(new HttpRequestEncoder())
//respon解码
.addLast(new HttpResponseDecoder())
.addLast(new HttpObjectAggregator(10240))
.addLast(netClientHandler);
}
});
try {
ChannelFuture future = client.connect("localhost", 8080).sync();
future.channel().writeAndFlush(httpParams()).sync();
future.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
//服务端返回的结果
System.out.println("服务端返回的结果\n"+netClientHandler.getResponse());
}
/**
* 构建FullHttpRequest 发送请求
* @return
* @throws URISyntaxException
*/
private static FullHttpRequest httpParams() throws URISyntaxException {
URI uri = new URI("?id=123");
FullHttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
HttpMethod.GET,
uri.toASCIIString());
return request;
}
}
- 客户端业务逻辑处理
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
/**
* @ClassName : NetClientHandler
* @Description : netty客户端处理
* @Author : 明心
* @Date: 2021-01-23
*/
public class NetClientHandler extends ChannelInboundHandlerAdapter {
private Object response;
public Object getResponse(){
return response;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//用FullHttpResponse解析服务器返回来的信息
FullHttpResponse res = (FullHttpResponse) msg;
ByteBuf content = res.content();
response=content.toString(CharsetUtil.UTF_8);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
}
}
- 效果