1. 程式人生 > >使用Netty實現自定義推送

使用Netty實現自定義推送

public class NettyClientHandler extends SimpleChannelInboundHandler<BaseMsg>{
//設定心跳時間 開始時間
public static final int MIN_CLICK_DELAY_TIME = 1000*30;
private int tryTime = 0;
public static final int MAX_TRY_TIME = 8;

private static Map<String, SocketChannel> Map = new ConcurrentHashMap<String, SocketChannel>();


@Override
protected void messageReceived(ChannelHandlerContext ctx, BaseMsg baseMsg) throws Exception {
// TODO Auto-generated method stub
switch (baseMsg.getType()) {
case LOGIN:

break;


case PONG:
System.out.println("接受到伺服器端的PONG");
break;

case PUSH:
PushMsg pushMsg =(PushMsg) baseMsg;
System.out.println("收到伺服器端的推送訊息:主題"+pushMsg.getTitle()+" 內容:"+pushMsg.getContent());
break;

default:
System.out.println("-------default--------");
break;
}
}

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
tryTime=0;
LoginMsg loginMsg = new LoginMsg();
loginMsg.setPassword("yao"+System.currentTimeMillis());
loginMsg.setUserName("robot"+System.currentTimeMillis());
final String clientId= System.currentTimeMillis()+"";
loginMsg.setClientId(clientId);
Map.put(clientId, (SocketChannel) ctx.channel());
//開啟執行緒進行ping
new Thread(new Runnable() {//每隔180秒傳送一個ping

public void run() {
while(true){
try {
Thread.sleep(1000*180);
PingMsg pingMsg = new PingMsg();
pingMsg.setClientId(clientId);
ctx.writeAndFlush(pingMsg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
ctx.writeAndFlush(loginMsg);
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 斷線後的操作
super.channelInactive(ctx);
tryTime++;
if(tryTime>MAX_TRY_TIME)
return;
System.out.println("從連線中。。。。。。。");
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
System.out.println("出現異常啦:"+cause.getMessage());
ctx.close();
}


}