客戶端要登陸,登陸成功以後服務器得告訴客戶端有沒有登陸成功,這時候服務器就要生成應答包了。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); } }