import java.io.Serializable;
public class Dog implements Serializable {
private String name;
private String type;
private String color;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class MsgEncoder extends MessageToByteEncoder<Dog> {
@Override
protected void encode(ChannelHandlerContext ctx, Dog msg, ByteBuf out) throws Exception {
byte[] body = convertToBytes(msg);
System.out.println("Dog convert to bytes");
if (body == null || body.length < 1) {
return;
}
int dataLength = body.length;
out.writeInt(dataLength);
out.writeBytes(body);
}
private byte[] convertToBytes(Dog dog) {
if (dog == null) {
return null;
}
try {
String contentString = JSON.toJSONString(dog);
return contentString.getBytes("GBK");
} catch (Exception e) {
System.out.println("Dog convert to bytes error. ");
e.printStackTrace();
}
return null;
}
}
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 MsgDecoder extends ByteToMessageDecoder {
private static final int HEAD_LENGTH = 4;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < HEAD_LENGTH) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (dataLength < 0) {
ctx.close();
}
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] body = new byte[dataLength];
in.readBytes(body);
Object o = convertToObject(body);
System.out.println("bytes convert to Dog");
out.add(o);
}
private Object convertToObject(byte[] body) {
if (body == null || body.length < 1) {
return null;
}
String contentString = null;
try {
contentString = new String(body, "GBK");
} catch (Exception e) {
}
if (contentString == null || contentString.length() < 1) {
return null;
}
try {
Dog dog = JSON.parseObject(contentString, Dog.class);
return dog;
} catch (Exception e) {
System.out.println("bytes convert to Dog error. ");
e.printStackTrace();
}
return contentString;
}
}
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
@Component
public class ObjectServer {
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
private static final EventLoopGroup work = new NioEventLoopGroup();
private int port = getPort();
public void close() {
System.out.println("关闭服务器....");
work.shutdownGracefully();
}
public void start() {
serverBootstrap.group(work)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO));
try {
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast( new MsgEncoder());
pipeline.addLast(new MsgDecoder());
pipeline.addLast(new ServerObjectHandler());
}
});
System.out.println("netty服务器在[" + port + "]端口启动监听");
ChannelFuture f = serverBootstrap.bind(port);
f.channel().closeFuture();
} catch (Exception e) {
System.out.println("[出现异常] 释放资源");
} finally {
close();
}
}
private static int getPort() {
Double port = (Math.random() + 1) * 10000;
return port.intValue();
}
public static void main(String[] args) {
ObjectServer nsl = new ObjectServer();
nsl.start();
public class ServerObjectHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("some error. ");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
Dog dog = (Dog) msg;
System.out.println(
"receive message. name=" + dog.getName() + ",type=" + dog.getType() + ",color=" + dog
.getColor()
);
Dog returnDog = new Dog();
returnDog.setName("MaoMao");
returnDog.setType("JinMao");
returnDog.setColor("yellow");
ctx.writeAndFlush(returnDog);
}
}