Http Client
HttpClient 客户端
package com.example.nettydemo.eyue.httpClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
public class HttpClient {
public void connect(String host, int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new HttpResponseDecoder());
ch.pipeline().addLast(new HttpRequestEncoder());
ch.pipeline().addLast(new HttpClientHandler());
}
});
ChannelFuture f = b.connect(host, port).sync();
System.out.println("netty http client connected on host(" + host + ") port(" + port + ")");
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new HttpClient().connect("127.0.0.1", 8801);
}
}
HttpClientHandler 处理类
package com.example.nettydemo.eyue.httpClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.nio.charset.StandardCharsets;
public class HttpClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
URI uri = new URI("http://127.0.0.1:8800:/test?data=100");
String content = "hello netty http Server!";
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
uri.toASCIIString(), Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
ctx.channel().writeAndFlush(request);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
ByteBuf buf = content.content();
System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
}
}
}
Http Server
NettyHttpServer 服务端
package com.example.nettydemo.eyue.httpserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
@Slf4j
public class NettyHttpServer implements Runnable{
int port ;
public NettyHttpServer(int port){
this.port = port;
}
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
@Override
public void run() {
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss,work)
.handler(new LoggingHandler(LogLevel.DEBUG))
.channel(NioServerSocketChannel.class)
.childHandler(new HttpServerInitializer());
ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
if (f.isSuccess()) {
System.out.println("HTTP服务端启动成功");
} else {
System.out.println("HTTP服务端启动失败");
f.cause().printStackTrace();
}
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
}
HttpServerInitializer 初始化类
package com.example.nettydemo.eyue.httpserver;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
System.out.println("初始化通道: Http server initChannel..");
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024));
pipeline.addLast(new HttpServerRequestHandler());
}
}
HttpServerRequestHandler 处理类
var foo = 'bar';package com.example.nettydemo.eyue.httpserver;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class HttpServerRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.CONTINUE));
}
SocketAddress socketAddress = ctx.channel().localAddress();
String str = socketAddress.toString();
System.out.println("ip"+str);
String str1=str.substring(0, str.indexOf(":"));
String str2=str.substring(str1.length()+1, str.length());
System.out.println("port: "+str2);
String uri = req.uri();
System.out.println("收到客户端发来的消息"+uri);
Map<String,String> resMap = new HashMap<>();
resMap.put("method",req.method().name());
resMap.put("uri",uri);
String msg = "你请求uri为:" + uri+"";
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服务端接收数据完毕..");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("hello client");
}
}
Tcp Client
RpcRequest 实体类
package com.example.nettydemo.eyue.entiy;
import lombok.Data;
@Data
public class RpcRequest {
private String id;
private Object data;
@Override
public String toString() {
return "RpcRequest{" + "id='" + id + '\'' + ", data=" + data + '}';
}
}
RpcResponse 实体类
package com.example.nettydemo.eyue.entiy;
import lombok.Data;
@Data
public class RpcResponse {
private String id;
private Object data;
private int status;
@Override
public String toString() {
return "RpcResponse{" + "id='" + id + '\'' + ", data=" + data + ", status=" + status + '}';
}
}
RpcEncoder 编码
package com.example.nettydemo.eyue;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class RpcEncoder extends MessageToByteEncoder {
private Class<?> target;
public RpcEncoder(Class target) {
this.target = target;
}
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
if (target.isInstance(msg)) {
byte[] data = JSON.toJSONBytes(msg);
out.writeInt(data.length);
out.writeBytes(data);
}
}
}
RpcDecoder 解码
package com.example.nettydemo.eyue;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class RpcDecoder extends ByteToMessageDecoder {
private Class<?> target;
public RpcDecoder(Class target) {
this.target = target;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < 4) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] data = new byte[dataLength];
in.readBytes(data);
Object obj = JSON.parseObject(data, target);
out.add(obj);
}
}
TcpClient 客户端
package com.example.nettydemo.eyue.tcpClient;
import com.example.nettydemo.eyue.entiy.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.SneakyThrows;
public class TcpClient {
private String ip;
private int port;
public TcpClient(String ip, int port){
this.ip = ip;
this.port = port;
this.connect(ip,port);
}
@SneakyThrows
public void connect(String host, int port){
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new TcpClientInitializer());
ChannelFuture f = b.connect(host, port).sync();
System.out.println("向 ip: " + host + " , port:" + port + " 的服务器 发送请求 ");
if(f.isSuccess()){
System.out.println("客户端启动成功");
} else {
System.out.println("客户端启动失败");
f.cause().printStackTrace();
}
RpcRequest rpcRequest = new RpcRequest();
rpcRequest.setId("100");
rpcRequest.setData("我是 tcp 客户端。。。。。。。。。。。。");
f.channel().writeAndFlush(rpcRequest);
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args){
new TcpClient("127.0.0.1", 8800);
}
}
TcpClientInitializer 初始化类
package com.example.nettydemo.eyue.tcpClient;
import com.example.nettydemo.eyue.RpcDecoder;
import com.example.nettydemo.eyue.RpcEncoder;
import com.example.nettydemo.eyue.entiy.RpcRequest;
import com.example.nettydemo.eyue.entiy.RpcResponse;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
public class TcpClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel){
System.out.println("初始化通道: Tcp client initChannel..");
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new RpcEncoder(RpcRequest.class));
pipeline.addLast(new RpcDecoder(RpcResponse.class));
pipeline.addLast(new TcpClientHandler());
}
}
TcpClientHandler 处理类
package com.example.nettydemo.eyue.tcpClient;
import com.example.nettydemo.eyue.entiy.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class TcpClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse response) throws Exception {
System.out.println("接受到server响应数据: " + response.toString());
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.err.println("客户端读取数据完毕");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.err.println("client 读取数据出现异常");
ctx.close();
}
}
Tcp Server
NettyTcpServer 服务端
package com.example.nettydemo.eyue.tcpserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
@Slf4j
public class NettyTcpServer implements Runnable{
int port ;
public NettyTcpServer(int port){
this.port = port;
}
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
@Override
public void run() {
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss,work)
.handler(new LoggingHandler(LogLevel.DEBUG))
.channel(NioServerSocketChannel.class)
.childHandler(new TcpServerInitializer());
ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
if (f.isSuccess()) {
System.out.println("Tcp服务端启动成功");
} else {
System.out.println("Tcp服务端启动失败");
f.cause().printStackTrace();
}
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
TcpServerInitializer 初始化类
package com.example.nettydemo.eyue.tcpserver;
import com.example.nettydemo.eyue.RpcDecoder;
import com.example.nettydemo.eyue.RpcEncoder;
import com.example.nettydemo.eyue.entiy.RpcRequest;
import com.example.nettydemo.eyue.entiy.RpcResponse;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
public class TcpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
System.out.println("初始化通道: Tcp server initChannel..");
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new RpcDecoder(RpcRequest.class));
pipeline.addLast(new RpcEncoder(RpcResponse.class));
pipeline.addLast(new TcpServerRequestHandler());
}
}
TcpServerRequestHandler 处理类
package com.example.nettydemo.eyue.tcpserver;
import com.example.nettydemo.eyue.entiy.RpcRequest;
import com.example.nettydemo.eyue.entiy.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.net.SocketAddress;
import java.util.UUID;
public class TcpServerRequestHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
SocketAddress socketAddress = ctx.channel().localAddress();
String str = socketAddress.toString();
System.out.println("ip"+str);
String str1=str.substring(0, str.indexOf(":"));
String str2=str.substring(str1.length()+1, str.length());
System.out.println("port: "+str2);
RpcRequest request = (RpcRequest) msg;
System.out.println("接收到客户端信息:" + request.toString());
RpcResponse response = new RpcResponse();
response.setId(UUID.randomUUID().toString());
response.setData("server响应结果");
response.setStatus(1);
ctx.writeAndFlush(response);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服务端接收数据完毕..");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("hello client");
}
}
ThreadPoolConfig 线程池配置类
package com.example.nettydemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(50);
taskExecutor.setQueueCapacity(200);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("myExecutor--");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
springboot 启动类
package com.example.nettydemo;
import com.example.nettydemo.config.ThreadPoolConfig;
import com.example.nettydemo.eyue.httpserver.NettyHttpServer;
import com.example.nettydemo.eyue.tcpserver.NettyTcpServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executor;
@EnableAsync
@SpringBootApplication
public class NettyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(NettyDemoApplication.class, args);
ThreadPoolConfig threadPoolConfig = new ThreadPoolConfig();
Executor executor = threadPoolConfig.taskExecutor();
executor.execute(new NettyTcpServer(8800));
executor.execute(new NettyHttpServer(8801));
}
}
结果
HTTP服务端启动成功
Tcp服务端启动成功
初始化通道: Tcp server initChannel..
ip/127.0.0.1:8800
port: 8800
接收到客户端信息:RpcRequest{id='100', data=我是 tcp 客户端。。。。。。。。。。。。}
服务端接收数据完毕..
初始化通道: Http server initChannel..
ip/127.0.0.1:8801
port: 8801
收到客户端发来的消息http://127.0.0.1:8800:/test?data=100