Socket网络通信编程--Netty
Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
换句话说,Netty是一个NIO框架,使用它可以简单快速的开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程中比如TCP和UDP的Socket开发。
“快速和简单”并不意味着应用程序会有难维护和低性能的问题,Netty是一个精心设计的框架,它从许多协议的实现中吸收了很多经验比如FTP、SMTP、HTTP、许多二进制基于文本的传统协议,Netty在不降低开发效率、性能、稳定性、灵活性的情况下,成功的找到了解决方案。
用户指南:http://ifeve.com/netty5-user-guide/
简单应用
server.java
package com.nettyTest;
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.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class Server {
private int port;
public Server(int port) {
this.port = port;
}
public void run() {
//用来接收连接事件组
EventLoopGroup boss = new NioEventLoopGroup();
//用来处理接收到的连接事件处理组
EventLoopGroup worker = new NioEventLoopGroup();
//server配置辅助类
ServerBootstrap bootstrap = new ServerBootstrap();
try {
//将连接接收组与事件处理组连接,当server的boss接收到连接收就会交给worker处理
bootstrap.group(boss, worker)
//指定channel类型
.channel(NioServerSocketChannel.class)
//handler会在初始化时就执行,而childHandler会在客户端成功connect后才执行
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ServerHandler());
}
})
//设置tcp缓冲区大小
.option(ChannelOption.SO_BACKLOG, 128)
//设置发送缓冲区大小
.option(ChannelOption.SO_SNDBUF, 1024 * 32)
//设置接收缓冲区大小
.option(ChannelOption.SO_RCVBUF, 1024 * 32)
//设置是否保存长连接
.childOption(ChannelOption.SO_KEEPALIVE, true);
//注意。此处option()是提供给NioServerSocketChannel用来接收进来的连接,也就是boss线程
//childOption是提供给有福管道serverChannel接收到的连接,也就是worker线程,在这个例子中也就是NioServerSocketChannel
//异步绑定端口,可以绑定多个端口
ChannelFuture fu1 = bootstrap.bind(port).sync();
ChannelFuture fu2 = bootstrap.bind(8766).sync();
//异步检查是否关闭
fu1.channel().closeFuture().sync();
fu2.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worker.shutdownGracefully();
boss.shutdownGracefully();
}
}
public static void main(String[] args) {
Server server = new Server(8765);
server.run();
}
}
ServerHandler.java
package com.nettyTest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class ServerHandler extends ChannelHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
System.out.println("Exception Caught...");
super.exceptionCaught(channelHandlerContext, throwable);
}
@Override
public void channelRead(final ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
try {
ByteBuf buf = (ByteBuf) o;
byte[] bt = new byte[buf.readableBytes()];
buf.readBytes(bt);
System.out.println("服务端接收到客户端请求:"+ new String(bt,"utf-8"));
ChannelFuture fu = channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(("hi client").getBytes()));
fu.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
System.out.println("服务端监听到数据反馈发送完毕");
channelHandlerContext.close();
}
});
fu.addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) {
e.printStackTrace();
}finally {
// write方法会自动释放,write后不是必须执行此方法,只有read方法后执行此方法
ReferenceCountUtil.release(channelHandlerContext);
}
}
}
Client.java
package com.nettyTest;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class Client {
private String ip;
private int port;
public Client(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void run(){
//客户端用来连接服务端的连接组
EventLoopGroup worker= new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ClientHandler());
}
})
.option(ChannelOption.SO_KEEPALIVE,true);
try {
//可以进多个端口同时连接
ChannelFuture fu1 = bootstrap.connect(ip,port).sync();
ChannelFuture fu2 = bootstrap.connect(ip,8766).sync();
fu1.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server").getBytes()));
fu2.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server8766").getBytes()));
fu1.channel().closeFuture().sync();
fu2.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
Client cl = new Client("127.0.0.1",8765);
cl.run();
}
}
ClientHandler.java
package com.nettyTest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf byteBuf = (ByteBuf) msg;
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
System.out.println("客户端接收反馈数据:" + new String(bytes,"utf-8"));
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
server端控制台
client端控制台
建立Netty通信服务的四个步骤:
1. 创建2个NIO线程组,一个专门用于网络时间处理(接收客户端的连接),另一个则进行网络通信读写
2. 创建一个ServerBootStrap对象,配置Netty的一系列参数,例如接收传出数据的缓存大小等
3. 创建一个实际处理数据的类ChannelInitializer,进行初始化的准备工作,比如设置接收或传出数据的字符集、格式、以及实际处理数据的端口
4. 绑定端口,执行同步阻塞方法等待服务器端启动即可。
在netty中,默认传输都输ByteBuf类型的,如果要以其他类型的格式,必须在配置ChanneIlnitializer的时候,需要配置影响的编码器和解码器(netty已经提供)。注意配置的时候服务端和客户端最好都要配置,否则没有配置的一方获取的还是ByteBuf。这里的演示代码只配置了server端,有兴趣的可以按照server自己去配置一下client端
package com.nettyString;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class Server {
private int port;
public Server(int port) {
this.port = port;
}
public void run() {
//用来接收连接事件组
EventLoopGroup boss = new NioEventLoopGroup();
//用来处理接收到的连接事件处理组
EventLoopGroup worker = new NioEventLoopGroup();
//server配置辅助类
ServerBootstrap bootstrap = new ServerBootstrap();
try {
//将连接接收组与事件处理组连接,当server的boss接收到连接收就会交给worker处理
bootstrap.group(boss, worker)
//指定channel类型
.channel(NioServerSocketChannel.class)
//handler会在初始化时就执行,而childHandler会在客户端成功connect后才执行
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new ServerHandler());
}
})
//设置tcp缓冲区大小
.option(ChannelOption.SO_BACKLOG, 128)
//设置发送缓冲区大小
.option(ChannelOption.SO_SNDBUF, 1024 * 32)
//设置接收缓冲区大小
.option(ChannelOption.SO_RCVBUF, 1024 * 32)
//设置是否保存长连接
.childOption(ChannelOption.SO_KEEPALIVE, true);
//注意。此处option()是提供给NioServerSocketChannel用来接收进来的连接,也就是boss线程
//childOption是提供给有福管道serverChannel接收到的连接,也就是worker线程,在这个例子中也就是NioServerSocketChannel
//异步绑定端口,可以绑定多个端口
ChannelFuture fu1 = bootstrap.bind(port).sync();
ChannelFuture fu2 = bootstrap.bind(8766).sync();
//异步检查是否关闭
fu1.channel().closeFuture().sync();
fu2.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worker.shutdownGracefully();
boss.shutdownGracefully();
}
}
public static void main(String[] args) {
Server server = new Server(8765);
server.run();
}
}
serverHandler
package com.nettyString;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class ServerHandler extends ChannelHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
System.out.println("Exception Caught...");
super.exceptionCaught(channelHandlerContext, throwable);
}
@Override
public void channelRead(final ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
try {
System.out.println("收到");
String str = (String) o;
System.out.println("服务端接收到客户端请求:"+str);
ChannelFuture fu = channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(("hi client").getBytes()));
fu.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
System.out.println("服务端监听到数据反馈发送完毕");
channelHandlerContext.close();
}
});
fu.addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) {
e.printStackTrace();
}finally {
ReferenceCountUtil.release(channelHandlerContext);
}
}
}
client
package com.nettyString;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class Client {
private String ip;
private int port;
public Client(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void run(){
//客户端用来连接服务端的连接组
EventLoopGroup worker= new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new ServerHandler());
socketChannel.pipeline().addLast(new ClientHandler());
}
})
.option(ChannelOption.SO_KEEPALIVE,true);
try {
//可以进多个端口同时连接
ChannelFuture fu1 = bootstrap.connect(ip,port).sync();
ChannelFuture fu2 = bootstrap.connect(ip,8766).sync();
fu1.channel().writeAndFlush("Hello Server$_");
fu2.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server8766").getBytes()));
fu1.channel().closeFuture().sync();
fu2.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
Client cl = new Client("127.0.0.1",8765);
cl.run();
}
}
clientHandler
package com.nettyString;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
/**
* Created by BaiTianShi on 2018/9/5.
*/
public class ClientHandler extends ChannelHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
ByteBuf byteBuf = (ByteBuf) msg;
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
System.out.println("客户端接收反馈数据:" + new String(bytes,"utf-8"));
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}