Server
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 Server {
private final Integer port;
public Server(Integer port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast(new ServerHandler());
}
});
System.out.println("Server is ready");
ChannelFuture cf = serverBootstrap.bind(this.port).sync();
cf.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
Server server = new Server(8080);
server.run();
}
}
ClientHandler
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;
public class ServerHandler extends SimpleChannelInboundHandler<String> {
private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
public void handlerAdded(ChannelHandlerContext context) {
Channel channel = context.channel();
channelGroup.writeAndFlush("【系统】" + channel.remoteAddress() + "上线了\n");
synchronized (channelGroup) {
channelGroup.add(channel);
}
}
public void channelActive(ChannelHandlerContext context) {
System.out.println("【log】" + context.channel().remoteAddress() + "上线了");
}
public void handlerRemoved(ChannelHandlerContext context) {
System.out.println("【log】" + context.channel().remoteAddress() + "下线了");
Channel channel = context.channel();
synchronized (channelGroup) {
channelGroup.remove(channel);
}
channelGroup.writeAndFlush("【系统】" + channel.remoteAddress() + "下线了\n");
}
@Override
protected void channelRead0(ChannelHandlerContext context, String s) {
System.out.println("【log】" + context.channel().remoteAddress() + "发送消息:" + s);
channelGroup.forEach(channel -> {
if(channel != context.channel()) {
channel.writeAndFlush("【用户】" + context.channel().remoteAddress() + "发送消息:" + s + "\n");
} else {
channel.writeAndFlush("【我】" + context.channel().remoteAddress() + "发送消息:" + s + "\n");
}
});
}
public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) {
System.out.println("【error】" + context.channel().remoteAddress() + "发生异常");
}
}
Client
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import java.util.Scanner;
public class Client {
private final String ip;
private final Integer port;
public Client(String ip, Integer port) {
this.ip = ip;
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new ClientHandler());
}
});
System.out.println("Client is ready");
Channel channel = bootstrap.connect(this.ip, this.port).sync().channel();
Scanner scanner = new Scanner(System.in);
String content = scanner.nextLine();
while(!content.equals("")) {
channel.writeAndFlush(content + "\r\n");
content = scanner.nextLine();
}
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
Client client = new Client("localhost", 8080);
client.run();
}
}
ClientHandler
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
}
public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) {
context.close();
}
}