netty参考 服务器端

netty参考 服务器端_第1张图片

 

package com.lenovo.lps.psb.ps.udp.handler;

import java.net.InetSocketAddress;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;

import com.lenovo.lps.log.Log;
import com.lenovo.lps.psb.PushServer;
import com.lenovo.lps.psb.ps.cache.STCache;
import com.lenovo.lps.psb.ps.manager.TransportManager;
import com.lenovo.lps.psb.ps.udp.UDPConnection;
import com.lenovo.lps.psb.ps.udp.vo.PushUDPUser;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.COMMAND_TYPE;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.TTL_INIT;

public class MessageHandler extends IdleStateAwareChannelHandler {
 private final static Log logger = Log.getInstance(MessageHandler.class);
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
   throws Exception {
//  Builder bulder = MESSAGE.newBuilder();
//  bulder.setId("ACKID:1000");
//  PUSH_MESSAGE pushMessage = PUSH_MESSAGE.newBuilder().setSid("sid")
//    .setBody("body:msg").build();
//  bulder.addPmsg(pushMessage);
//  // bulder.setPmsg(0, pushMessage);
//  MESSAGE massage = bulder.build();
//  PUSH_UDP_COMMAND comm = PUSH_UDP_COMMAND.newBuilder().setId(1000)
//    .setMessage(massage).setType(COMMAND_TYPE.MESSAGE).build();
//  // channel.write(comm,udpConn.getPushUDPUser().getSocketAddress());
//  PushUDPUser pushUDPUser = new PushUDPUser();
//  // pushUDPUser.setUser_name(udpConn.getPushUDPUser().getSocketAddress()+"");
//  pushUDPUser.setSocketAddress(e.getRemoteAddress());
//  PushUDPServerHandler.send(pushUDPUser, comm, e.getChannel(), true);

  
  PUSH_UDP_COMMAND command = (PUSH_UDP_COMMAND) e.getMessage();
  if(command ==null){
   return;
  }
  if (COMMAND_TYPE.TTL_INIT.equals(command.getType())) {
   
//   TTLINITEvent ttlEvent = (TTLINITEvent) e;
   String ipAddress = TTLINITHandler.getIPAdress(e);
   TTL_INIT ttlInit = command.getTtlInit();
   STCache stCache = (STCache) PushServer.getBean("stCache");
   String lpsst = ttlInit.getSt();
   logger.info("USER LOGIN: " + command);
   InetSocketAddress inetSocketAddress=(InetSocketAddress) e.getRemoteAddress();
   String pidStr = lpsst;//inetSocketAddress.getPort()+"";
//   try {
//    pidStr = USS.getPid(lpsst);
//   } catch (Exception e1) {
//    logger.info("USS ERROR: " + e1.getMessage());
//
//    PushUDPUser pushUDPUser = new PushUDPUser();
//    pushUDPUser.setUser_name(ipAddress);
//    pushUDPUser.setSocketAddress(e.getRemoteAddress());
//    PushUDPServerHandler.send(pushUDPUser, PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.ST_VALIDATE_ERR,-1), e.getChannel(), true);
//    return;
//   }
//   if (pidStr == null || pidStr.length() == 0) {
//    PushUDPUser pushUDPUser = new PushUDPUser();
//    pushUDPUser.setUser_name(ipAddress);
//    pushUDPUser.setSocketAddress(e.getRemoteAddress());
//    PushUDPServerHandler.send(pushUDPUser, PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.ST_NULL_ERR,-1), e.getChannel(), true);
//    logger.info("ERROR:" + lpsst);
//    return;
//   }
   long pid = Long.valueOf(pidStr);

   logger.info("pid: " + pid);
   try {
    stCache.saveST(ipAddress, pid + "");
   } catch (Exception e1) {
    e1.printStackTrace();
   }
   
   int clientTTL = ttlInit.getTtl();
   int netType = ttlInit.getNetType();
   int cellID = ttlInit.getCellID();
   int operatorCode = ttlInit.getOptCode();
   String ip = TTLINITHandler.getIP(e);
   int ttl = TTLINITHandler.getTTL(clientTTL, netType, ip, cellID,operatorCode);

   TransportManager tm = (TransportManager) PushServer
     .getBean("transportManager");
   UDPConnection udpConn = tm.getDevice(pid);

   
   PushUDPUser user = new PushUDPUser();
   user.setUser_name(ipAddress);
   user.setSocketAddress(e.getRemoteAddress());
   user.setCurrentTtl(ttl);
   user.setCellID(cellID);
   user.setNetType(netType);
//   user.setPreviousTtl(ttl);
   user.setOperatorCode(operatorCode);
   user.setPid(pid);
   
   
   if (udpConn == null) {
    udpConn = (UDPConnection) PushServer.getBean("udpConnection");
    udpConn.setPid(Long.valueOf(pid));
    udpConn.setPushUDPUser(user);
//    PollVO pollVO = new PollVO();
////    pollVO.setPid(Long.valueOf(pid));
//    pollVO.setRequestTime(System.currentTimeMillis());
//    udpConn.setPollVO(pollVO);
    tm.handle(udpConn);

    logger.info("User " + lpsst+ " Login !");

//    new DeviceCacheTest(user);

   } else {
    udpConn.setPushUDPUser(user);
    logger.info("User " + lpsst + " Relogin !");
   }
   
   //test
   /*
   Gson gson =new Gson();
   String s = gson.toJson(udpConn);
   +":Gson:"+s
   */
   //syn nid
   tm.setCacheUDPNid(pid);

   logger.info("TTL_INIT:ST:" + lpsst
     + ";Message Lenth:" + lpsst.getBytes().length
     + ":TTL:" + udpConn.getPushUDPUser().getCurrentTtl());
   
   PushUDPServerHandler.send(udpConn.getPushUDPUser(),PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.SUCCESS, ttl), e.getChannel(),false);
   
   PushUDPServerHandler.send(udpConn.getPushUDPUser(),PushUDPServerHandler.getTTLTry(ttl), e.getChannel(),false);
  }else {
   UpstreamMessageEvent upstreamMessageEvent= new UpstreamMessageEvent(ctx.getChannel(),
     command, e.getRemoteAddress());
   ctx.sendUpstream(upstreamMessageEvent);
  }
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.lenovo.lps.psb.ps.udp.handler;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;

import com.lenovo.lps.log.Log;
import com.lenovo.lps.psb.PushServer;
import com.lenovo.lps.psb.common.log.BizActionConstants;
import com.lenovo.lps.psb.common.vo.DevPollRespXmlVO;
import com.lenovo.lps.psb.common.vo.DeviceMsgXmlVO;
import com.lenovo.lps.psb.ps.cache.STCache;
import com.lenovo.lps.psb.ps.manager.TransportManager;
import com.lenovo.lps.psb.ps.udp.UDPConnection;
import com.lenovo.lps.psb.ps.udp.task.MessageAckTask;
import com.lenovo.lps.psb.ps.udp.vo.PushUDPUser;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.COMMAND_TYPE;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.MESSAGE;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.MESSAGE.Builder;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.MESSAGE.PUSH_MESSAGE;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.MESSAGE_ACK;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.TTL_INIT_ACK;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.TTL_TRY;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.TTL_TRY_ACK;

public class PushUDPServerHandler extends IdleStateAwareChannelHandler {

 private final static Log logger = Log
   .getInstance(PushUDPServerHandler.class);

 public static int ST_VALIDATE_ERR = 530;
 public static int ST_NULL_ERR = 400;
 public static int SUCCESS = 0;
 public static AtomicInteger globalID = new AtomicInteger();

 private static final ExecutorService executor = new ThreadPoolExecutor(10,
   200, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
   throws Exception {
  PUSH_UDP_COMMAND command = (PUSH_UDP_COMMAND) e.getMessage();
  if (command != null) {
   // InetSocketAddress inet = (InetSocketAddress)
   // e.getRemoteAddress();
   // String ip = inet.getAddress().getHostAddress();
   // int host = inet.getPort();
   String lpsst = null;
   long pid = 0;
   String ipAddress = TTLINITHandler.getIPAdress(e);
   logger.debug("messageReceived: " + command.getType());

   STCache stCache = (STCache) PushServer.getBean("stCache");
   lpsst = stCache.getST(ipAddress);
   if (lpsst == null || lpsst.length() == 0) {
    send(new PushUDPUser(ipAddress,e.getRemoteAddress()), getTtlInitAck(ST_NULL_ERR, -1),
      e.getChannel(), true);
    logger.biz(Log.OPERATOR_DEVICE, pid, Log.STRING_NULL,
      BizActionConstants.ACTION_UDP_ST, Log.LONG_NULL, Log.STRING_NULL,
      Log.RESULT_FAILED, "ERROR:ST:PID:" + pid + ":IP:" + ipAddress);
    return;
   }
   pid = Long.valueOf(lpsst);
   TransportManager tm = (TransportManager) PushServer
     .getBean("transportManager");
   UDPConnection udpConn = tm.getDevice(pid);
   //处理TTL轮询器发消息给终端时间
   delayKeepAlive(udpConn.getPushUDPUser());
   //改为 switch
   if (COMMAND_TYPE.TTL_TRY_ACK.equals(command.getType())) {
    TTL_TRY_ACK initAck = command.getTtlTryAck();
    int ttl = initAck.getTtl();
    PushUDPUser user = udpConn.getPushUDPUser();
    if (user != null) {
     // if (ttl <= user.getCurrentTtl()) {
     int new_ttl = ttl  > 1 ? (ttl - 1) : 1;
     if (new_ttl > PushUDPUser.TTL_INIT) {
      new_ttl = PushUDPUser.TTL_INIT - 1;
     }
     user.setCurrentTtl(new_ttl);
     logger.debug("TTL_ACK;IP:" + ipAddress + ";TTLTRY:"
       + user.getCurrentTtl());
     if (new_ttl > 1) {
      send(user, getTTLTry(user.getCurrentTtl()),
        e.getChannel(), false);
     }
     // }
    }
//    logger.info("TTL_TRY_ACK:PID:" + pid + ":IP:" + ipAddress
//      + ":TTL:" + user.getCurrentTtl());
    logger.biz(Log.OPERATOR_DEVICE, pid, Log.STRING_NULL,
      BizActionConstants.ACTION_UDP_TTL_ACK, Log.LONG_NULL, Log.STRING_NULL,
      Log.RESULT_SUCCEED, "TTL_TRY_ACK:PID:" + pid + ":IP:" + ipAddress
      + ":TTL:" + user.getCurrentTtl());

   } else if (COMMAND_TYPE.MESSAGE_ACK.equals(command.getType())) {
    MESSAGE_ACK msgAck = command.getMessageAck();
    executor.execute(new MessageAckTask(udpConn, tm, msgAck.getId()));
//    logger.info("MESSAGE_ACK:PID:" + pid + ":ACK_ID:"
//      + msgAck.getId());
    logger.biz(Log.OPERATOR_DEVICE, pid, Log.STRING_NULL,
      BizActionConstants.ACTION_UDP_MSG_ACK, Log.LONG_NULL, Log.STRING_NULL,
      Log.RESULT_SUCCEED, "MESSAGE_ACK:PID:" + pid + ":ACK_ID:"
      + msgAck.getId());
    
   } else if (COMMAND_TYPE.MESSAGE_NULL_ACK.equals(command.getType())) {
    tm.setCacheUDPNid(pid);
//    logger.info("MESSAGE_NULL_ACK:PID:" + pid);
    logger.biz(Log.OPERATOR_DEVICE, pid, Log.STRING_NULL,
      BizActionConstants.ACTION_UDP_MSG_NULL_ACK, Log.LONG_NULL, Log.STRING_NULL,
      Log.RESULT_SUCCEED, "MESSAGE_NULL_ACK:PID:" + pid);
   }
   
  }
 }
 
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
   throws Exception {
  logger.error(e.getCause());
  super.exceptionCaught(ctx, e);
 }

 void delayKeepAlive(PushUDPUser user){
  long currentTime = System.currentTimeMillis();
  user.setAckKeepAliveTime(currentTime
    + PushUDPUser.ACK_KEEPALIVE_TIME_DEFAULT);
  user.setKeepAliveTime(currentTime+PushUDPUser.KEEPALIVE_TIME_DEFAULT);
  user.setDeviceTimeOutRetry(0);
 }

// @Override
// public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
//   throws IOException {
//  if (e.getState() == IdleState.READER_IDLE) {
//   // e.getChannel().close();
//  } else if (e.getState() == IdleState.WRITER_IDLE) {
//
//   // logger.info("channelIdle: ");
//   // TransportManager tm = (TransportManager) PushServer
//   // .getBean("transportManager");
//   //
//   // Iterator iter = tm.getAllDevice().entrySet().iterator();
//   // while (iter.hasNext()) {
//   // Map.Entry entry = (Map.Entry) iter.next();
//   //
//   // UDPConnection udpConn = (UDPConnection) entry.getValue();
//   // PushUDPUser user = udpConn.getPushUDPUser();
//   // // if (user.getCurrentTtl() == user.getPreviousTtl()) {
//   // if (user.getTtlRery() >= 20) {
//   // TTLCache ttlCache = (TTLCache) PushServer
//   // .getBean("ttlCache");
//   // InetSocketAddress inet = (InetSocketAddress) user
//   // .getSocketAddress();
//   // String ip = inet.getAddress().getHostAddress();
//   // if (user.getNetType() == PushUDPUser.WIFI) {
//   // ttlCache.saveWifiTTL(ip, user.getCurrentTtl());
//   // } else {
//   // ttlCache.saveMobileTTL(ip, user.getCellID(),
//   // user.getCurrentTtl());
//   // }
//   // user.setTtlRery(0);
//   // // }
//   // user.setTtlRery(user.getTtlRery() + 1);
//   // } else {
//   // user.setTtlRery(0);
//   // }
//   // send(udpConn.getPushUDPUser(), getTTLTry(udpConn
//   // .getPushUDPUser().getCurrentTtl()), ctx.getChannel(),
//   // false);
//   //
//   // }
//
//  }
// }
//

 public static PUSH_UDP_COMMAND getMessageNull() {
  PUSH_UDP_COMMAND command = PUSH_UDP_COMMAND.newBuilder()
    .setId(globalID.incrementAndGet())
    .setType(COMMAND_TYPE.MESSAGE_NULL)
    .setVer(1).build();
  return command;
 }

 public static PUSH_UDP_COMMAND getTtlInitAck(int errCode, int ttl) {
  TTL_INIT_ACK ttlInitAck = TTL_INIT_ACK.newBuilder().setErrCode(errCode)
    .setTtl(ttl).build();
  PUSH_UDP_COMMAND command = PUSH_UDP_COMMAND.newBuilder()
    .setId(globalID.incrementAndGet())
    .setType(COMMAND_TYPE.TTL_INIT_ACK).setTtlInitAck(ttlInitAck)
    .setVer(1)
    .build();
  return command;
 }

 public static PUSH_UDP_COMMAND getTTLTry(int ttl) {
  TTL_TRY ttlTry = TTL_TRY.newBuilder().setTtl(ttl).setPeriod(PushUDPUser.ACK_KEEPALIVE_TIME_DEFAULT/1000).build();
  PUSH_UDP_COMMAND command = PUSH_UDP_COMMAND.newBuilder()
    .setId(globalID.incrementAndGet())
    .setType(COMMAND_TYPE.TTL_TRY).setTtlTry(ttlTry)
    .setVer(1).build();
  return command;
 }

 public static PUSH_UDP_COMMAND getMessage(String idcid, long repId,
   List<DeviceMsgXmlVO> deviceMsgXmlVOList) {
  Builder bulder = MESSAGE.newBuilder();
  bulder.setId(idcid + DevPollRespXmlVO.ACK_separator + repId);
  for (int i = 0; i < deviceMsgXmlVOList.size(); i++) {
   DeviceMsgXmlVO deviceMsgXmlVO = deviceMsgXmlVOList.get(i);
   PUSH_MESSAGE pushMessage = PUSH_MESSAGE.newBuilder()
     .setSid(deviceMsgXmlVO.getSid())
     .setBody(deviceMsgXmlVO.getBody()).build();
   bulder.addPmsg(pushMessage);
   logger.debug("Get and Send message, sid[" + deviceMsgXmlVO.getSid()
     + "],message[" + deviceMsgXmlVO.getBody() + "]");
  }
  MESSAGE massage = bulder.build();
  PUSH_UDP_COMMAND command = PUSH_UDP_COMMAND.newBuilder()
    .setId(globalID.incrementAndGet()).setMessage(massage)
    .setType(COMMAND_TYPE.MESSAGE)
    .setVer(1).build();
  return command;
 }

 public static synchronized void send(PushUDPUser user,
   PUSH_UDP_COMMAND command, Channel channel, boolean isDefaultTTL)
   throws IOException {
//  logger.info("WRITE start time:[" + System.nanoTime() + "]");
  logger.debug("WRITE TO PID:[" + user.getPid() + "] UserName:["
    + user.getUser_name() + "]: <TTL:" + (isDefaultTTL?PushUDPUser.TTL_DEFAULT:user.getCurrentTtl())
    + ",Address:" + user.getSocketAddress() + ">,msg:" + command);

  if (isDefaultTTL) {
   channel.setTimeToLive(PushUDPUser.TTL_DEFAULT);
  } else {
   channel.setTimeToLive(user.getCurrentTtl());
  }
  // String[] userNameArr= user.getUser_name().split(":");
  // InetSocketAddress inet = new InetSocketAddress(userNameArr[0],
  // Integer.valueOf(userNameArr[1]));
  channel.write(command, user.getSocketAddress());
//  logger.info("WRITE end time:[" + System.nanoTime() + "]");
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.lenovo.lps.psb.ps.udp.handler;

import java.net.InetSocketAddress;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;

import com.lenovo.lps.jpcap.TTLInitNotifier;
import com.lenovo.lps.log.Log;
import com.lenovo.lps.psb.PushServer;
import com.lenovo.lps.psb.common.log.BizActionConstants;
import com.lenovo.lps.psb.ps.cache.STCache;
import com.lenovo.lps.psb.ps.cache.TTLCache;
import com.lenovo.lps.psb.ps.manager.TransportManager;
import com.lenovo.lps.psb.ps.udp.UDPConnection;
import com.lenovo.lps.psb.ps.udp.vo.PushUDPUser;
import com.lenovo.lps.userservice.serveragent.LpsAuthentication;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.COMMAND_TYPE;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND.TTL_INIT;

public class TTLINITHandler extends IdleStateAwareChannelHandler {
 private final static Log logger = Log.getInstance(TTLINITHandler.class);

 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
   throws Exception {
  PUSH_UDP_COMMAND command = (PUSH_UDP_COMMAND) e.getMessage();
  if(command ==null){
   return;
  }
  if (COMMAND_TYPE.TTL_INIT.equals(command.getType())) {
   
   String ipAddress = getIPAdress(e);
   TTL_INIT ttlInit = command.getTtlInit();
   STCache stCache = (STCache) PushServer.getBean("stCache");
   String lpsst = ttlInit.getSt();
   
   logger.info("USER LOGIN: " + command);
//   String pidStr = null;
   long pid ;
   //验证ST
   try {
    LpsAuthentication ussAuth =(LpsAuthentication) PushServer.getBean("ussAuthen");
    pid =ussAuth.handleTicketValidation(lpsst).getID();
//    pidStr = USS.getPid(lpsst);
   } catch (Exception e1) {
    logger.warn("USS ERROR: " + e1.getMessage(), e1);
    PushUDPServerHandler.send(new PushUDPUser(ipAddress,e.getRemoteAddress()), PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.ST_VALIDATE_ERR,-1), e.getChannel(), true);
    return;
   }
   if (pid <= 0) {
    PushUDPServerHandler.send(new PushUDPUser(ipAddress,e.getRemoteAddress()), PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.ST_NULL_ERR,-1), e.getChannel(), true);
    logger.warn("ERROR:" + lpsst);
    return;
   }
//   long pid = Long.valueOf(pidStr);
//   logger.biz(operator_type, operator_id, operator_name, action, resource_id, resource_name, result, des);
   logger.info("pid: " + pid);
   try {
    stCache.saveST(ipAddress, pid + "");
   } catch (Exception e1) {
    logger.error("ERROR to save st ," + e1.getMessage());
   }
   
//   int clientTTL = ttlInit.getTtl();
   int netType = ttlInit.getNetType();
   int cellID = ttlInit.getCellID();
   int operatorCode = ttlInit.getOptCode();
   String ip = getIP(e);
   Integer ttl = TTLInitNotifier.ttl_init_list.get(ip);//getTTL(clientTTL, netType, ip, cellID,operatorCode);
   if(ttl == null || ttl < 1 ){
    ttl = PushUDPUser.TTL_INIT;
   }else{
    ttl+=PushUDPUser.TTL_RANGE;
   }
   TransportManager tm = (TransportManager) PushServer
     .getBean("transportManager");
   UDPConnection udpConn = tm.getDevice(pid);
   
   long currentTime = System.currentTimeMillis();
   if (udpConn == null) {
   
    udpConn = (UDPConnection) PushServer.getBean("udpConnection");
    
    PushUDPUser user  = new PushUDPUser();
    
    user.setUser_name(ipAddress);
    user.setSocketAddress(e.getRemoteAddress());
    user.setCurrentTtl(ttl);
    user.setCellID(cellID);
    user.setNetType(netType);
//    user.setPreviousTtl(ttl);
    user.setOperatorCode(operatorCode);
    user.setPid(pid);
    user.setAckKeepAliveTime(currentTime
      + PushUDPUser.ACK_KEEPALIVE_RETRY_TIME_DEFAULT);
    user.setKeepAliveTime(currentTime
      + PushUDPUser.KEEPALIVE_TIME_DEFAULT);
    
    udpConn.setPid(Long.valueOf(pid));
    udpConn.setPushUDPUser(user);
    tm.handle(udpConn);
    logger.info("User " + lpsst+ " Login !");
   } else {
    
    PushUDPUser user = udpConn.getPushUDPUser();
    if(user == null){
     user = new PushUDPUser();
    }
    
    user.setUser_name(ipAddress);
    user.setSocketAddress(e.getRemoteAddress());
    user.setCurrentTtl(ttl);
    user.setCellID(cellID);
    user.setNetType(netType);
//    user.setPreviousTtl(ttl);
    user.setOperatorCode(operatorCode);
    user.setPid(pid);
    user.setAckKeepAliveTime(currentTime
      + PushUDPUser.ACK_KEEPALIVE_RETRY_TIME_DEFAULT);
    user.setKeepAliveTime(currentTime
      + PushUDPUser.KEEPALIVE_TIME_DEFAULT);
    
    udpConn.setPushUDPUser(user);
    logger.info("User " + lpsst + " Relogin !");
   }
   
   //test
   /*
   Gson gson =new Gson();
   String s = gson.toJson(udpConn);
   +":Gson:"+s
   */
   //syn nid
   tm.setCacheUDPNid(pid);
   //检查消息
   tm.respond(udpConn);
   
//   logger.info("TTL_INIT:ST:" + lpsst
//     + ";Message Lenth:" + lpsst.getBytes().length
//     + ":TTL:" + udpConn.getPushUDPUser().getCurrentTtl());
   logger.biz(Log.OPERATOR_DEVICE, pid, Log.STRING_NULL,
     BizActionConstants.ACTION_UDP_ST, Log.LONG_NULL, Log.STRING_NULL,
     Log.RESULT_SUCCEED, "TTL_INIT:ST:" + lpsst
     + ";Message Lenth:" + lpsst.getBytes().length
     + ":TTL:" + udpConn.getPushUDPUser().getCurrentTtl());
   PushUDPServerHandler.send(udpConn.getPushUDPUser(),PushUDPServerHandler.getTtlInitAck(PushUDPServerHandler.SUCCESS, ttl), e.getChannel(),true);
   
   PushUDPServerHandler.send(udpConn.getPushUDPUser(),PushUDPServerHandler.getTTLTry(ttl), e.getChannel(),false);
  }else {
   UpstreamMessageEvent upstreamMessageEvent= new UpstreamMessageEvent(ctx.getChannel(),
     command, e.getRemoteAddress());
   ctx.sendUpstream(upstreamMessageEvent);
  }

 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
   throws Exception {
  logger.error(e.getCause());
  super.exceptionCaught(ctx, e);
 }
 static int getTTL(int clientTTL, int netType, String ip, int cellID,int operatorCode) {
  int ttl = 0;
  TTLCache ttlCache = (TTLCache) PushServer.getBean("ttlCache");
  try {
//  switch(netType){
//  case PushUDPUser.WIFI:
    ttl = ttlCache.getWifiTTL(ip);
//   break;
//  default:
//   ttl = ttlCache.getMobileTTL(ip, cellID+"",operatorCode+"");
//  }
   } catch (Exception e) {
    e.printStackTrace();
   }
   
  if (ttl <= 0) {
   ttl = Integer.valueOf(clientTTL);
  }
  
  return ttl <= 0 || ttl > PushUDPUser.TTL_INIT ? PushUDPUser.TTL_INIT
    : ttl+PushUDPUser.TTL_RANGE;
 }

 static String getIP(MessageEvent e) {
  InetSocketAddress inet = (InetSocketAddress) e.getRemoteAddress();
  return inet.getAddress().getHostAddress();
 }

 static String getIPAdress(MessageEvent e){
  InetSocketAddress inet = (InetSocketAddress) e.getRemoteAddress();
  String ip = inet.getAddress().getHostAddress();
  int host = inet.getPort();
  return ip + ":" + host;
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.lenovo.lps.psb.ps.udp.pipeline;

import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

import com.lenovo.lps.psb.ps.udp.handler.MessageHandler;
import com.lenovo.lps.psb.ps.udp.handler.PushUDPServerHandler;
import com.lenovo.lps.psb.ps.udp.handler.TTLINITHandler;
import com.lenovo.lsf.push.net.protobuf.PushUDPCommandProtos.PUSH_UDP_COMMAND;


public class PushUDPServerPipelineFactory implements ChannelPipelineFactory{

// private final Timer timer;
// private final ChannelHandler idleStateHandler;
 
 public PushUDPServerPipelineFactory(){
//  this.timer = timer;
//        this.idleStateHandler = new IdleStateHandler(timer, 0, idle, 0);Timer timer,int idle
 }
    public ChannelPipeline getPipeline() throws Exception {
     ChannelPipeline pipeline = Channels.pipeline();
      // Decoders
      pipeline.addLast("frameDecoder",
                       new ProtobufVarint32FrameDecoder());
      pipeline.addLast("protobufDecoder",
                       new ProtobufDecoder(PUSH_UDP_COMMAND.getDefaultInstance()));

      // Encoder
      pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
      pipeline.addLast("protobufEncoder", new ProtobufEncoder());
//      pipeline.addLast("idleStateHandler", idleStateHandler);
//      pipeline.addLast("messageHandler", new MessageHandler());
      pipeline.addLast("ttlINITHandler", new TTLINITHandler());
      pipeline.addLast("pushUDPServer", new PushUDPServerHandler());
      return pipeline;

    }
}

 

你可能感兴趣的:(netty参考 服务器端)