1.ProtoMgr.java
package com.my.Game.Proto;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class ProtoMgr {
static private GsonBuilder gb = new GsonBuilder();
static private final Gson gson;
static {
gb.disableHtmlEscaping();
gson = gb.create();
}
/**
* json编码器
*
* @param ctype
* @param body
* @return
*/
public static String jsonEncode(int ctype, Object body) {
String json = gson.toJson(new Body(ctype, body));
return json;
}
/**
* json解码器
*
* @param json
* @param tClass
* @param <T>
* @return
*/
public static <T> T jsonDecode(String json, Class<T> tClass) {
T t = JSON.parseObject(json, tClass);
return t;
}
private static class Body {
public int ctype;
public Object body;
public Body(int ctype, Object body) {
this.ctype = ctype;
this.body = body;
}
}
}
2.IOHandler.java
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
if (webSocketFrame instanceof TextWebSocketFrame) {
String str = ((TextWebSocketFrame) webSocketFrame).text();
logger.info(str);
int ctype = 2;
Object body = new TestResp();
String strResp = ProtoMgr.jsonEncode(ctype, body);
channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(strResp));
} else {
String message = webSocketFrame.getClass().getName();
logger.error("无法处理的类型{}", message);
}
}
复杂的数据类型
package com.my.Game.Proto;
import java.util.ArrayList;
import java.util.Arrays;
public class TestResp {
public int age = 22;
public ArrayList<Rank> rankList = new ArrayList<>(Arrays.asList(new Rank(), new Rank(), new Rank(), new Rank(), new Rank()));
static private class Rank {
public int rank = 1;
public ArrayList<String> nameList = new ArrayList<>(Arrays.asList("jn", "xx", "cx"));
}
}
来源:oschina
链接:https://my.oschina.net/u/4266664/blog/4254313