简单的聊天
服务端
ChatServer
public class ChatServer {
private int port;
public ChatServer(int port) {
this.port = port;
}
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap strap = new ServerBootstrap();
strap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChatServerInitializer())
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
System.out.println("[系统消息]: 服务器启动完毕!");
ChannelFuture sync = strap.bind(port).sync();
sync.channel().closeFuture().sync();
}catch (Exception e){
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
System.out.println("[系统消息]: 服务器关闭!");
}
}
public static void main(String[] args) throws Exception{
int port = 8080;
new ChatServer(port).run();
}
}
ChatServerInitializer
public class ChatServerInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ChatServerHandler());
System.out.println("SimpleChatClient:"+ socketChannel.remoteAddress() +"连接上");
}
}
ChatServerHandler
public class ChatServerHandler extends SimpleChannelInboundHandler<String>{
public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel inComing = ctx.channel();
for(Channel channel : channels){
if(channel != inComing){
channel.writeAndFlush("[系统消息]: " + inComing.remoteAddress() + "上线了!\n");
}
}
channels.add(inComing);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel inComing = ctx.channel();
for(Channel channel : channels){
if(channel != inComing){
channel.writeAndFlush("[系统消息]: " + inComing.remoteAddress() + "下线了!\n");
}
}
channels.remove(inComing);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel incoming = ctx.channel();
for (Channel channel : channels) {
if (channel != incoming){
channel.writeAndFlush("[用户 " + incoming.remoteAddress() + "]: " + msg + "\n");
} else {
channel.writeAndFlush("[我]: " + msg + "\n");
}
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel inComing = ctx.channel();
System.out.println("[" +inComing.remoteAddress()+ "]: "+"在线中");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel inComing = ctx.channel();
System.out.println("[" +inComing.remoteAddress()+ "]: "+"离线中");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Channel incoming = ctx.channel();
System.out.println("SimpleChatClient:"+incoming.remoteAddress()+"异常");
System.out.println("出现异常");
ctx.close();
}
}
客户端
ChatClient
public class ChatClient {
private String host;
private int port;
public ChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run(){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChatClientInitializer());
Channel channel = bootstrap.connect(host, port).sync().channel();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
channel.writeAndFlush(reader.readLine() + "\n");
}
}catch (Exception e){
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args){
String host = "localhost";
int port = 8080;
new ChatClient(host, port).run();
}
}
ChatClientInitializer
public class ChatClientInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new ChatClientHandler());
}
}
ChatClientHandler
public class ChatClientHandler extends SimpleChannelInboundHandler<String>{
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
}
}