在
Netty(一)之helloworld https://blog.csdn.net/qq_37171353/article/details/100180406
的基础之上修改
org.objenesis
objenesis
2.6
com.dyuproject.protostuff
protostuff-api
1.0.10
com.dyuproject.protostuff
protostuff-core
1.0.10
com.dyuproject.protostuff
protostuff-runtime
1.0.10
io.netty
netty-all
5.0.0.Alpha1
public class MsgInfo {
private Integer id;
private String msg;
//getter setter 构造方法省略。。。
}
我看了很多博客,写的大体都差不多这个样子,这里不需要要改动
ObjSerializationUtil
package protostuff;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author CBeann
* @create 2019-09-24 20:01
*/
public class ObjSerializationUtil {
private static Map, Schema>> cachedSchema = new ConcurrentHashMap<>();
private static Objenesis objenesis = new ObjenesisStd();
private ObjSerializationUtil() {
}
/**
* 序列化(对象 -> 字节数组)
*
* @param obj 对象
* @return 字节数组
*/
public static byte[] serialize(T obj) {
Class cls = (Class) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化(字节数组 -> 对象)
*
* @param data
* @param cls
* @param
*/
public static T deserialize(byte[] data, Class cls) {
try {
T message = objenesis.newInstance(cls);
Schema schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private static Schema getSchema(Class cls) {
Schema schema = (Schema) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
cachedSchema.put(cls, schema);
}
return schema;
}
}
ObjDecoder
package protostuff;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* @author CBeann
* @create 2019-09-24 19:53
*/
public class ObjDecoder extends ByteToMessageDecoder {
private Class> genericClass;
public ObjDecoder(Class> genericClass) {
this.genericClass = genericClass;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List
ObjEncoder
package protostuff;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* @author CBeann
* @create 2019-09-24 20:03
*/
public class ObjEncoder extends MessageToByteEncoder {
private Class> genericClass;
public ObjEncoder(Class> genericClass) {
this.genericClass = genericClass;
}
@Override
protected void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) {
if (genericClass.isInstance(in)) {
byte[] data = ObjSerializationUtil.serialize(in);
out.writeInt(data.length);
out.writeBytes(data);
}
}
}
修改的一样
//对象传输处理
socketChannel.pipeline().addLast(new ObjDecoder(MsgInfo.class));
socketChannel.pipeline().addLast(new ObjEncoder(MsgInfo.class));
//发送数据
MsgInfo msgInfo =
new MsgInfo(1, "客户端:--->" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
f.channel().writeAndFlush(msgInfo);
Thread.sleep(4000);
msgInfo = new MsgInfo(1, "客户端:--->" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
f.channel().writeAndFlush(msgInfo);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//服务器读客户端发送来的数据
MsgInfo msgInfo = (MsgInfo) msg;
System.out.println("The TimeServer receive :" + msgInfo);
//服务器向客户端回应请求
msgInfo = new MsgInfo(2, "服务端:--->" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
ctx.writeAndFlush(msgInfo);
}
//客户端读取服务器发送的数据
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
//服务器读客户端发送来的数据
MsgInfo msgInfo = (MsgInfo) msg;
System.out.println("客户端收到 : " + msg);
} catch (Exception e) {
e.printStackTrace();
} finally {
//标配
ReferenceCountUtil.release(msg);
}
}
项目代码下载
链接:https://pan.baidu.com/s/1gmbNwmAb3gEZX-c1XvYdQQ
提取码:w7w1
复制这段内容后打开百度网盘手机App,操作更方便哦
https://mp.weixin.qq.com/s?__biz=MzIxMDAwMDAxMw==&mid=2650724806&idx=1&sn=bb986119b9cdd950e2e6d995295e7f06&scene=19#wechat_redirect
https://blog.csdn.net/qq_18860653/article/details/77649229