客户端要登陆,登陆成功以后服务器得告诉客户端有没有登陆成功,这时候服务器就要生成应答包了。java
咱们的数据交互使用了ProtoBuf,下面是proto源文件:android
option java_package = "com.cdeer.protobuf"; //定义protobuf的包名称空间 option java_outer_classname = "CdeerMsg";// 消息体名称 /*顶层消息*/ message Message { required int32 header = 1; // 包头 optional LoginInfo login_info = 2; // 登陆信息 optional LoginSuccess login_success = 3; // 登陆成功 optional ErrorInfo error_info = 4; // 错误信息 } /** header 包头说明: 101--登录请求; 801--登陆成功; 200--心跳请求ping; 201--心跳响应pong; 500--消息回执; 102--单聊; 404--错误消息; 502--已读消息; 505--正在输入; 900--退出登陆; */ /*登陆信息*/ message LoginInfo{ required int64 user_id = 1; // 用户id required string token = 2; // 用户token optional string platform = 3; // 客户端平台:android,ios,web optional string app_version = 4; // APP版本号 } /*登陆成功*/ message LoginSuccess{ } /*错误消息*/ message ErrorInfo{ required int32 code = 1; //错误码 required string info = 2; //错误描述 required int32 expose = 3; //错误描述是否提示给用户:1 提示;0 不提示 } /*单聊消息*/ message ChatMsg{ optional int64 msg_id = 1; //消息id optional int64 from = 2; //发送方id optional int64 to = 3; //接收方id optional int64 time = 4; //时间戳(单位:毫秒) required int32 msg_type = 5; //消息类型 optional string content = 6; //消息内容 optional string url = 7; //多媒体地址 optional string property = 8; //附加属性 optional string from_nick = 9; //发送者昵称 optional string json = 10; //附加的json串 }
用ProtoBuf生成的java文件中加入了set和get方法,下面就是设置包头的方法:ios
public Builder setHeader(int value) { bitField0_ |= 0x00000001; header_ = value; onChanged(); return this; }
若是客户端登陆成功,那么就开始构造应答消息:web
/** * 发送登陆成功消息 * * @param channel */ public static void routeLoginSuccess(Channel channel) { LoginSuccess.Builder loginSuccess = LoginSuccess.newBuilder(); Message.Builder msg2 = Message.newBuilder(); msg2.setHeader(801); msg2.setLoginSuccess(loginSuccess); Message msgSend = msg2.build(); routeDerict(channel, msgSend); }
routeDerict是用来直接发送消息的方法:json
/** * 直接发送消息 * * @param channel * 通道 * @param msgSend * 要发送的消息 */ public static void routeDerict(Channel channel, Message msgSend) { try { channel.writeAndFlush(msgSend); } catch (Exception e) { Log.error(e.getMessage(), e); } }