package nchart;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class Cser {
private int port;
public Cser(int port) {
this.port = port;
}
public void sta() throws InterruptedException {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup work = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss,work).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,123).childOption(ChannelOption.SO_KEEPALIVE,true).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("dec", new StringDecoder());
pipeline.addLast("cod", new StringEncoder());
pipeline.addLast(new CShandler());
}
});
ChannelFuture future = serverBootstrap.bind(port).sync();
future.channel().closeFuture().sync();
}
public static void main(String[] args) throws Exception{
new Cser(12345).sta();
}
}
package nchart;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
public class CShandler extends SimpleChannelInboundHandler<String> {
public static final DefaultChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
CHANNELS.writeAndFlush(ctx.channel().remoteAddress()+":来了");
CHANNELS.add(ctx.channel());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + ":上线了");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + ":离线了");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel channel = ctx.channel();
CHANNELS.forEach(ch->{
if (ch != channel) {
ch.writeAndFlush(channel.remoteAddress() + "说:" + msg);
}else {
ch.writeAndFlush("我说:" + msg);
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
CHANNELS.writeAndFlush(channel.remoteAddress()+":无连接了");
System.out.println(channel.remoteAddress()+":无连接了");
}
}