这里不再详细介绍netty是什么,可以网上查资料学习
直接开干~~~~
package nettypro.netty.groupchat;
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;
/**
* @ClassName GroupChatServer
* @Description netty服务器
* @Author zeny
* @Date 2020/3/24 0024 21:13
*/
public class GroupChatServer {
private int port;
private GroupChatServer(int port) {
this.port = port;
}
/**
ChannelOption.SO_BACKLOG, 128 : 对应 TCP/IP 协议 listen 函数中的 backlog 参数,用来初始化服务器可连接队列大小。服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog 参数指定了队列的大小;
ChannelOption.SO_KEEPALIVE, true: 一直保持连接活动状态
*/
public void run(){
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup(8);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//加入解码器
pipeline.addLast("decoder", new StringDecoder());
//加入编码器
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast(new GroupChatServerHandler());
}
});
System.out.println("netty server is starting......");
ChannelFuture channelFuture = bootstrap.bind(this.port).sync();
channelFuture.channel().closeFuture().sync();
}catch (Exception e) {
}finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args){
new GroupChatServer(8888).run();
}
}
package nettypro.netty.groupchat;
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 org.aspectj.apache.bcel.generic.NEW;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName GroupChatServerHandler
* @Description 具体处理
* @Author zeny
* @Date 2020/3/24 0024 21:26
*/
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
//定义一个channel组,管理所有的channel,GlobalEventExecutor.INSTANCE 是全局事件执行器,单例
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* @Description 连接时首先执行,保存每个channel,并给所有channel提示
* @Date 2020/3/24 0024 21:32
* @param ctx
* @return void
**/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
//给每个channel发送消息
channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "在 " + simpleDateFormat.format(new Date()) + " 加入聊天\n");
channelGroup.add(channel);
}
/**
* @Description channel处于活动状态,提示xxx上线
* @Date 2020/3/24 0024 21:38
* @param ctx
* @return void
**/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + "上线了......");
}
/**
* @Description channel离线
* @Date 2020/3/24 0024 21:40
* @param ctx
* @return void
**/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + "离线了......");
}
/**
* @Description 断开连接,并提示给在线用户
* @Date 2020/3/24 0024 21:41
* @param ctx
* @return void
**/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//自动移除当前channel
channelGroup.writeAndFlush("[客户端]" + ctx.channel().remoteAddress() + " 离开了......\n");
}
/**
* @Description 处理数据
* @Date 2020/3/24 0024 21:43
* @param ctx
* @param msg
* @return void
**/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel channel = ctx.channel();
channelGroup.forEach(ch -> {
if (ch != channel) {
//不是当前channel,转发
ch.writeAndFlush("[客户]" + channel.remoteAddress() + " 说: " + msg + "\n");
}else {
ch.writeAndFlush("[自己] 说: " + msg + "\n");
}
});
}
/**
* @Description 处理异常
* @Date 2020/3/24 0024 21:48
* @param ctx
* @param cause
* @return void
**/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
这个handler
添加在pipeline
里面
package nettypro.netty.groupchat;
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 java.util.Scanner;
/**
* @ClassName GroupChatClient
* @Description 客户端
* @Author zeny
* @Date 2020/3/24 0024 21:53
*/
public class GroupChatClient {
private final String host;
private final int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast(new GroupChatClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();
Channel channel = channelFuture.channel();
System.out.println("--------" + channel.localAddress() + "--------");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
//发送内容
String msg = scanner.nextLine();
channel.writeAndFlush(msg + "\r\n");
}
}catch (Exception e) {
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) {
new GroupChatClient("127.0.0.1", 8888).run();
}
}
package nettypro.netty.groupchat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @ClassName GroupChatClientHandler
* @Description TODO
* @Author zeny
* @Date 2020/3/24 0024 22:06
*/
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//服务器发过来的内容
System.out.println(msg.trim());
}
}