/
ServerHandler.java
55 lines (42 loc) · 1.73 KB
/
ServerHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.shinemo.mpush.core.handler;
import com.shinemo.mpush.api.protocol.Packet;
import com.shinemo.mpush.api.Connection;
import com.shinemo.mpush.api.Receiver;
import com.shinemo.mpush.core.ConnectionManager;
import com.shinemo.mpush.core.NettyConnection;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by ohun on 2015/12/19.
*/
public class ServerHandler extends ChannelHandlerAdapter {
private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
private final Receiver receiver;
public ServerHandler(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Connection connection = ConnectionManager.INSTANCE.get(ctx.channel());
receiver.onReceive((Packet) msg, connection);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ConnectionManager.INSTANCE.remove(ctx.channel());
log.error(ctx.channel().remoteAddress() + ", exceptionCaught", cause);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
log.warn(ctx.channel().remoteAddress() + ", channelActive");
Connection connection = new NettyConnection();
connection.init(ctx.channel());
ConnectionManager.INSTANCE.add(connection);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.warn(ctx.channel().remoteAddress() + ", channelInactive");
ConnectionManager.INSTANCE.remove(ctx.channel());
}
}