package com.thhy.staff.modules.biz.netty;
|
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import javax.websocket.Session;
|
import java.util.concurrent.CopyOnWriteArraySet;
|
|
|
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
|
|
private Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
|
|
/**
|
* 线程安全的无序的集合
|
*/
|
public static final CopyOnWriteArraySet<ChannelHandlerContext> CTXS = new CopyOnWriteArraySet<>();
|
|
/**
|
* 客户端连接会触发
|
*/
|
@Override
|
public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
CTXS.add(ctx);
|
logger.info("Channel active......");
|
}
|
|
|
|
/**
|
* 客户端发消息会触发
|
*/
|
@Override
|
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
logger.info("服务器收到消息: {}", msg.toString());
|
ctx.write("recive success");
|
ctx.flush();
|
}
|
|
/**
|
* 发生异常触发
|
*/
|
@Override
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
CTXS.remove(ctx);
|
logger.info("chucuo"+cause.getMessage());
|
cause.printStackTrace();
|
ctx.close();
|
}
|
|
}
|