Netty傻瓜教程(六):開始點對點聊天吧

首先Netty服務器收到了消息:java

@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg)
			throws Exception {

		// message 解析
		Message receiveMsg = (Message) msg;
		// 相應的Handler
		AppMsgHandler msgHandler = AppMsgHandlerFactory
				.getAppMsgHandler(receiveMsg);
		if (msgHandler != null) {
			msgHandler.process(ctx.channel(), receiveMsg);
		} else {
			// 沒找到相應的handler
			Log.error("no handler,msg2:" + receiveMsg.toString());
		}
	}

1. AppMsgHandlerFactory.getAppMsgHandler(receveMsg),獲取處理特定消息類型的Handler,好比識別是登錄信息,仍是單聊信息,仍是心跳信息,或是心跳應答等等。若是不爲空,則對消息進行處理,調用msgHandler.process(ctx.channel(), receiveMsg),這裏傳入兩個參數,ctx.channel()就是標識每一個會話的通道。數據庫

若是收到的是登錄信息:服務器

@Override
	public void process(Channel channel, Message msg) {

		try {
			LoginInfo loginInfo = msg.getLoginInfo();
			long userId = loginInfo.getUserId();
			String token = loginInfo.getToken();
			String platform = loginInfo.getPlatform().toLowerCase();
			String appVersion = loginInfo.getAppVersion();

			Log.info(LogTAGManager.CLIENT_LOGIN_INFO + "userId:" + userId
					+ LogTAGManager.LOG_SEPARATE_PARAMS + "token:" + token
					+ LogTAGManager.LOG_SEPARATE_PARAMS + "platform:"
					+ platform + LogTAGManager.LOG_SEPARATE_PARAMS
					+ "appversion:" + appVersion);

			// token驗證
			String user_token = RedisDBProvider.getUserInfo(userId,
					"user_token");
			if ((user_token == null || "".equals(user_token) || (!user_token
					.equals(token)))) {
				int code = 1;
				String info = "登陸驗證失敗";
				int expose = 1;
				AppRouterManager
						.routeError(channel, code, info, expose, userId);
				channel.close();
				return;
			}

登錄成功以後,若是客戶端又發來了聊天信息,那麼識別信息的toUserId,從數據庫裏面查一下此用戶有沒有登錄,若是已經登錄,那麼調用SendMsg(channel, toUserId)便可。app

相關文章
相關標籤/搜索