1、服务端
package mynetty_study.netty.nettytest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
*类名:NettyServer.java
*类的描述信息:
*创建时间:上午11:42:00
**/
public class NettyServer {
//创建用于接收客户端连接请求
private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
//创建用于处理Socketchannel输入输出的
private static final EventLoopGroup handleGroup = new NioEventLoopGroup();
private static final int port = 8888;
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
//设置group
serverBootstrap.group(bossGroup, handleGroup)
//设置要被实例化的类
.channel(NioServerSocketChannel.class)
//设置Channel处理器
.childHandler(new ChannelInitializer<Channel>(){
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline cp = ch.pipeline();
//添加帧限定符来防止粘包
//粘包:
// 只有TCP有粘包现象,UDP永远不会粘包
// 发送端需要等缓冲区满才发送出去,造成粘包(发送数据时间间隔很短,数据了很小,会当做一个包发出去,产生粘包)
// 接收方不及时接收缓冲区的包,造成多个包接收(客户端发送了一段数据,服务端只收了一小部分,服务端下次再收的时候还是从缓冲区拿上次遗留的数据,产生粘包)
cp.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4))
//配置编解码
.addLast(new StringDecoder(CharsetUtil.UTF_8))
.addLast(new StringEncoder(CharsetUtil.UTF_8))
//配置业务逻辑实现类
.addLast(new TCPServerHandler());
}
});
try {
ChannelFuture future = serverBootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package mynetty_study.netty.nettytest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
*类名:TCPServerHandler.java
*类的描述信息:
*服务相关的设置的代码写完之后,我们再来编写主要的业务代码。 使⽤用Netty编写 [业务层 ]的代码,
*我们需要继承 ChannelInboundHandlerAdapter 或 SimpleChannelInboundHandler 类,在这
*里里顺便便说下它们两的区别吧。 继承 SimpleChannelInboundHandler 类之后,会在接收到数据后会
*自动 release 掉数据占⽤用的 Bytebuffer 资源。并且继承该类需要指定数据格式。 ⽽而继
*承ChannelInboundHandlerAdapter 则不不会⾃自动释放,需要⼿手动调⽤用
*ReferenceCountUtil.release() 等⽅方法进⾏行行释放。继承该类不不需要指定数据格式。 所以在这⾥里里,个⼈人
*推荐服务端继承 ChannelInboundHandlerAdapter ,⼿手动进⾏行行释放,防⽌止数据未处理理完就⾃自动释放
*了了。而且服务端可能有多个客户端进⾏行行连接,并且每⼀一个客户端请求的数据格式都不不⼀一致,这时便便可
*以进行相应的处理理。 客户端根据情况可以继承 SimpleChannelInboundHandler 类。好处是直接指
*定好传输的数据格式,就不不需要再进⾏行行格式的转换了了
*创建时间:下午2:28:03
**/
public class TCPServerHandler extends ChannelInboundHandlerAdapter {
//连接成功时候执行的操作
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//System.out.println("连接成功");
}
//执行读写
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
//执行会话
System.out.println("客户端:"+msg);
System.out.print("我:");
Scanner scan = new Scanner(System.in);
String str = scan.next();
ctx.channel().writeAndFlush(str);
ctx.close();
}
//异常处理
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("打印异常日志:"+cause.getStackTrace());
}
}
2、客户端
package mynetty_study.netty.nettytest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import java.util.Scanner;
import mynetty_study.netty.netty1.MyClient;
/**
*类名:NettyClient.java
*类的描述信息:
*创建时间:下午7:55:30
**/
public class NettyClient implements Runnable{
private static final int port = 8888;
private static final String ip = "127.0.0.1";
public static void main(String[] args) {
new Thread(new NettyClient()).start();
}
@Override
public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap boot = new Bootstrap();
//设置group
boot.group(group);
//设置要被实例化的类
boot.channel(NioSocketChannel.class)
//设置TCP方式的通信
.option(ChannelOption.TCP_NODELAY, true)
//设置SocketChannel处理器
.handler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldPrepender(4));
//设置编解码
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new TcpClient());
}
});
//执行会话
boolean check = true;
while(check){
ChannelFuture future = boot.connect(ip, port).sync();
System.out.print("我:");
Scanner sc=new Scanner(System.in);
String str=sc.next();
future.channel().writeAndFlush(str);
future.channel().closeFuture().sync();
if(str.equals("bye")){
check=false;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
group.shutdownGracefully();
}
}
}
package mynetty_study.netty.nettytest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class TcpClient extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("服务端:"+msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println(cause.getStackTrace());
}
}
3、效果