package com.sgg.tcp.protocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* @description:
* @date : 2020/6/7 19:00
* @author: zwz
*/
public class NettyClient {
public static void main(String[] args) throws InterruptedException {
//客户端需要一个事件循环组
EventLoopGroup eventExecutors = new NioEventLoopGroup();
//创建客户端启动对象
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(eventExecutors) //设置线程组
.channel(NioSocketChannel.class) //设置客户端通道的实现类
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyMessageToByteEncoder())
.addLast(new MyMessageToByteDecoder())
.addLast(new NettyClientHandler()); //加入自己的处理器
}
});
System.out.println("客户端 ok...");
//启动客户端去连接服务器端
//涉及到netty的异步模型
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
//给关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} finally {
eventExecutors.shutdownGracefully();
}
}
}
package com.sgg.tcp.protocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
/**
* @description: 自定义一个Handler 需要继续 netty 绑定好的某个 HandlerAdapter
* @date : 2020/6/7 18:44
* @author: zwz
*/
public class NettyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
private int count;
/**
* 当通道就绪就会触发该方法
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client " + ctx);
for (int i = 0; i < 5; ++i) {
String mes = "今天天气冷,吃火锅";
byte[] context = mes.getBytes(CharsetUtil.UTF_8);
//创建协议包对象
MessageProtocol messageProtocol = new MessageProtocol();
messageProtocol.setLen(context.length);
messageProtocol.setContent(context);
ctx.writeAndFlush(messageProtocol);
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
//接收到数据并处理
int len = msg.getLen();
byte[] content = msg.getContent();
System.out.println("客户端接收的消息如下");
System.out.println("长度=" + len);
System.out.println("内容" + new String(content, CharsetUtil.UTF_8));
System.out.println("客户端接收到的消息数量=" + (++this.count));
}
//处理异常 需要关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
package com.sgg.tcp.protocol;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
/**
* @description:
* @date : 2020/6/7 18:23
* @author: zwz
*/
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//创建BossGroup和WorkerGroup
//1. 创建两个线程组
//2. bossGroup只是处理连接请求,真正的和客户端业务处理,会交给workerGroupo完成
//3. 两个都是无限循环
//4. bossGroup 和 workGroup 含有的子线程的个数
//默认实际 CPU 核数*2=8。在不传参数的情况下有8个 线程。我的24个线程
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
//创建服务器端的启动对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
try {
//使用链式编程设置
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG, 128) //设置线程队列的连接个数
.childHandler(new ChannelInitializer<SocketChannel>() { //创建一个通道测试对象-匿名对象
//给pipeline设置处理器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//可以使用一个集合管理 socketChannel,再推送消息,
// 可以将业务加入到各个 channel 对应的 NIOEventLoop 的 taskQueue 或者 ScheduleTaskQueue
System.out.println("客户 socketChannel hashCode=" + ch.hashCode());
ch.pipeline().addLast(new MyMessageToByteDecoder()) //编解码器在前。否则会数据传输
.addLast(new MyMessageToByteEncoder())
.addLast(new NettyServerHandler());
}
}); //给我们的 workerGroup 的EventLoop对应的管道设置处理器
System.out.println("服务器准备好了");
//绑定一个端口并同步,生成一个 ChannelFuture 对象
//启动服务器
ChannelFuture future = bootstrap.bind(6668).sync();
//对关闭通道进行监听
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.sgg.tcp.protocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/**
* @description: 自定义一个Handler 需要继续 netty 绑定好的某个 HandlerAdapter
* @date : 2020/6/7 18:44
* @author: zwz
*/
public class NettyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
private int count;
@Override
protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
//接收到数据并处理
int len = msg.getLen();
byte[] content = msg.getContent();
System.out.println("\n\n");
System.out.println("服务器接收到的信息如下 ");
System.out.println("长度=" + len);
System.out.println("内容=" + new String(content, CharsetUtil.UTF_8));
System.out.println("服务器接收到的消息包数量" + (++count));
//回复的消息
String responseContent = UUID.randomUUID().toString();
byte[] bytes = responseContent.getBytes(StandardCharsets.UTF_8);
MessageProtocol messageProtocol = new MessageProtocol();
messageProtocol.setLen(bytes.length);
messageProtocol.setContent(bytes);
System.out.println("回复的消息:" + responseContent);
ctx.writeAndFlush(messageProtocol);
}
//处理异常 需要关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
package com.sgg.tcp.protocol;
/**
* @description: 协议包
* @date : 2020/6/8 21:06
* @author: zwz
*/
public class MessageProtocol {
private int len;
private byte[] content;
public int getLen() {
return len;
}
public void setLen(int len) {
this.len = len;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}
package com.sgg.tcp.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import java.util.List;
/**
* @description:
* @date : 2020/6/8 21:13
* @author: zwz
*/
public class MyMessageToByteDecoder extends ReplayingDecoder<Void> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
System.out.println("MyMessageToByteDecoder decode 方法被调用" );
//需要将得到的二进制字节码 转换为 MessageProtocol 数据包(对象)
int length = in.readInt(); //这里读取的实际就是 MessageProtocol 中的 len 字段(在handler中指定了就是消息的字节数组长度)
byte[] context = new byte[length];
in.readBytes(context);
//封装成 MEssageProtocol 对象,放入 out,传递下一个 handler 业务处理
MessageProtocol messageProtocol = new MessageProtocol();
messageProtocol.setLen(length);
messageProtocol.setContent(context);
out.add(messageProtocol);
}
}
package com.sgg.tcp.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* @description:
* @date : 2020/6/8 21:13
* @author: zwz
*/
public class MyMessageToByteEncoder extends MessageToByteEncoder<MessageProtocol> {
@Override
protected void encode(ChannelHandlerContext ctx, MessageProtocol msg, ByteBuf out) throws Exception {
System.out.println("MyMessageEncorder encode 方法被调用" );
out.writeInt(msg.getLen());
out.writeBytes(msg.getContent());
}
}
网友评论