<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">去官网下载Netty包,导入jar文件即可</span>
客服端代码
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class TimeClient {
public void connect(int port, String host) throws Exception {
// 创建客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();//启动NIO服务的辅助启动类,为了降低服务端的开发复杂度
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
//创建NioSocketChannel成功之后,初始化的时候将它的SocketChannel设置到ChannelPipeline中用于处理网络IO事件。
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
// 阻塞等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 释放NIO线程组
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
new TimeClient().connect(port, "127.0.0.1");
}
}
</pre><pre name="code" class="java">
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.logging.Logger;
public class TimeClientHandler extends ChannelHandlerAdapter {
private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
private final ByteBuf firstMessage;
//初始化要发送的数据
public TimeClientHandler() {
byte[] req = "当前时间是:".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(firstMessage); //发送信息给服务器
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];//获得缓冲区可读的字节数组,用于创建新的字节数组
buf.readBytes(req);//将缓冲区的字节数组复制到新创建的字节数组中
String body = new String(req, "UTF-8");
System.out.println(body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.print("异常?");
// 释放资源
logger.warning("Unexpected exception from downstream : "
+ cause.getMessage());
ctx.close();
}
}
服务端代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TimeServer {
public void bind(int port) throws Exception {
// 配置服务端的NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();//接受客服的链接
EventLoopGroup workerGroup = new NioEventLoopGroup();//进行SocketChannel的读写操作
try {
ServerBootstrap b = new ServerBootstrap();//启动NIO服务的辅助启动类,为了降低服务端的开发复杂度
/* 将两个NIO加入到ServerBootstrap中,接着创建Channel为NIOServerSocketChannel,相当于ServerSocketChannel类。
配置NIOServerSocketChannel的TCP参数将块大小设置成1024.最后绑定IO事件的处理类ChildChannelHander,主要处理网络IO事件对信息进行编解码等。*/
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());
// 绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
//阻塞等待, 等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
//释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
//创建NioSocketChannel成功之后,初始化的时候将它的SocketChannel设置到ChannelPipeline中用于处理网络IO事件。
arg0.pipeline().addLast(new TimeServerHandler());
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
new TimeServer().bind(port);
}
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
//读取信息
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];//获取缓冲区可读的字节数,根据字节数创建byte数组,
buf.readBytes(req);//将缓冲区的字节数组复制到新建的字节数组中,
String body = new String(req, "UTF-8");
System.out.println("客服端发来的信息:" + body);
//发送信息
Date time = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = simpleDateFormat.format(time);
String str = body + s;
ByteBuf resp = Unpooled.copiedBuffer(str.getBytes());
ctx.write(resp);//异步将信息发送给客服端
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();//将消息发送列队中的消息写入到SocketChannel中发送给对方
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.print("异常");
ctx.close();//关闭资源
}
}