TCPServerHandler.java
2.6 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.huaheng.pc.config.sn.tcp;
import com.alibaba.druid.support.json.JSONUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {
//定义一个channle 组,管理所有的channel
//GlobalEventExecutor.INSTANCE) 是全局的事件执行器,是一个单例
public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
/**
* 有客户端与服务器发生连接时执行此方法
* 1.打印提示信息
* 2.将客户端保存到 channelGroup 中
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.err.println("有新的客户端与服务器发生连接。客户端地址:" + channel.remoteAddress());
channelGroup.add(channel);
}
/**
* 当有客户端与服务器断开连接时执行此方法,此时会自动将此客户端从 channelGroup 中移除
* 1.打印提示信息
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
System.err.println("有客户端与服务器断开连接。客户端地址:" + channel.remoteAddress());
}
/**
* 表示channel 处于活动状态
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 处于活动状态");
}
/**
* 表示channel 处于不活动状态
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 处于不活动状态");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
String client=ctx.channel().remoteAddress().toString();
log.info("收到客户端消息IP:/n"+ client);
log.info("收到客户端消息:/n"+ msg);
// Object parse = JSONUtils.parse(msg);
System.out.println("parse = " + msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("TCPServer出现异常", cause);
ctx.close();
}
}