代码使用的是5.0.0.Alpha2版本netty
服务端Demo:
/**
* createtime : 2021年7月21日 下午3:20:22
*/
package com.testnetty.testmycodec;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* TODO
* @author XWF
*/
public class TestNettyCodecServer {
/**
* @param args
*/
public static void main(String[] args) {
ServerBootstrap bootstrap = new ServerBootstrap();
NioEventLoopGroup bossgroup = new NioEventLoopGroup();
NioEventLoopGroup workergroup = new NioEventLoopGroup();
bootstrap.group(bossgroup, workergroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new MyServerDecoder());
p.addLast(new MyServerEncoder());
p.addLast(new MyServerHandler());
}
});
try {
ChannelFuture future = bootstrap.bind(1234).sync();
if (future.isSuccess()) {
System.out.println("服务端启动成功。");
}
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossgroup.shutdownGracefully();
workergroup.shutdownGracefully();
}
}
}
class MyServerHandler extends SimpleChannelInboundHandler<String>{
@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("received:" + msg);
ctx.writeAndFlush("response date:" + new Date());//收到消息给客户端回发一条
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("+Active:" + ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("+Inactive:" + ctx);
}
}
class MyServerDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() > 0) {
System.out.println(">>>my server decoder");
byte[] bytes = new byte[in.readableBytes()];
in.readBytes(bytes);
System.out.println(">>>" + new String(bytes));
String decodeMsg = new String(bytes).toUpperCase();//收到客户端的消息字母转大写
System.out.println(">>>decodeMsg:" + decodeMsg);
out.add(decodeMsg);
}
}
}
class MyServerEncoder extends MessageToByteEncoder<String>{
@Override
protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
if (msg != null) {
System.out.println(">>>my server encoder");
System.out.println(">>>" + msg);
byte[] encodeMsg = Base64.getEncoder().encode(msg.getBytes());//给客户端发消息用Base64编码
System.out.println(">>>encodeMsg:" + new String(encodeMsg));
out.writeBytes(encodeMsg);
}
}
}
客户端Demo:
/**
* createtime : 2021年7月21日 下午3:20:43
*/
package com.testnetty.testmycodec;
import java.net.InetSocketAddress;
import java.util.Base64;
import java.util.List;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* TODO
* @author XWF
*/
public class TestNettyCodecClient {
/**
* @param args
*/
public static void main(String[] args) {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup workergroup = new NioEventLoopGroup();
bootstrap.group(workergroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.localAddress(3333);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new MyClientDecoder());
p.addLast(new MyClientEncoder());
p.addLast(new MyClientHander());
}
});
try {
ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 1234)).sync();
if (future.isSuccess()) {
System.out.println("客户端启动成功。");
}
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workergroup.shutdownGracefully();
}
}
}
class MyClientHander extends SimpleChannelInboundHandler<String> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("连接到服务端。");
ctx.writeAndFlush("abcDEF123");//连接后发送一个消息
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("断开连接。");
}
@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("received:" + msg);
}
}
class MyClientDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() > 0) {
byte[] bytes = new byte[in.readableBytes()];
in.readBytes(bytes);
System.out.println("### before decode:" + new String(bytes));
String decodeMsg = new String(Base64.getDecoder().decode(bytes));//base64解码
System.out.println("after decode:" + decodeMsg);
out.add(decodeMsg);
}
}
}
class MyClientEncoder extends MessageToByteEncoder<String> {
@Override
protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
if (msg != null) {
System.out.println("### before encode:" + msg);
msg = "[" + msg + "]";
System.out.println("after encode:" + msg);
out.writeBytes(msg.getBytes());
}
}
}
运行结果: