https://baike.baidu.com/item/Netty/10061624?fr=aladdin
百度百科:
“Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
“快速”和“简单”并不用产生维护性或性能上的问题。Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性。”
这里官网下载了Netty源码,
https://netty.io/downloads.html
并且跑通了demo
导包什么的就不说了百度奥
在此分享我的demo
东西都在注释里奥
就相当于cs框架
留handler给业务
内部封装了
SimpleServerHandler类
package Test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
/**
* 本方法用于读取客户端发送的信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleServerHandler.channelRead");
ByteBuf result = (ByteBuf) msg;
byte[] result1 = new byte[result.readableBytes()];
// msg中存储的是ByteBuf类型的数据,把数据读取到byte[]中
result.readBytes(result1);
String resultStr = new String(result1);
// 接收并打印客户端的信息
System.out.println("Client said:" + resultStr);
// 释放资源,这行很关键
result.release();
// 向客户端发送消息
String response = "hi 麻瓜!";
// 在当前场景下,发送的数据必须转换成ByteBuf数组
ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
encoded.writeBytes(response.getBytes());
ctx.write(encoded);
ctx.flush();
}
/**
* 本方法用作处理异常
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
}
/**
* 信息获取完毕后操作
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
SimpleClientHandler类
package Test;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
/**
* 本方法用于接收服务端发送过来的消息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleClientHandler.channelRead");
ByteBuf result = (ByteBuf) msg;
byte[] result1 = new byte[result.readableBytes()];
result.readBytes(result1);
System.out.println("Server said:" + new String(result1));
result.release();
}
/**
* 本方法用于处理异常
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 当出现异常就关闭连接
cause.printStackTrace();
ctx.close();
}
/**
* 本方法用于向服务端发送信息
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String msg = "hello 这里是麻瓜!";
ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
encoded.writeBytes(msg.getBytes());
ctx.write(encoded);
ctx.flush();
}
}
ServerTest 类
package Test;
//import com.lk.netty.mulchat.dome.ServerIniterHandler;
//import com.lk.netty.mulchat.dome.ServerMain;
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 org.omg.CORBA.PRIVATE_MEMBER;
/**
* 服务端生产者对象
* This is an netty Server
*
* Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,
* 例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。
*/
public class ServerTest {
/**
* 服务端口
*/
private int port=54111;
// private int port=9999;
/**
* 开启服务的方法
*/
public void StartNetty(){
EventLoopGroup acceptor = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
//1、创建启动类
ServerBootstrap bootstrap = new ServerBootstrap();
//2、配置启动参数等
/**设置循环线程组,前者用于处理客户端连接事件,后者用于处理网络IO(server使用两个参数这个)
*public ServerBootstrap group(EventLoopGroup group)
*public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)
*/
bootstrap.group(acceptor,worker);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
//用于构造socketchannel工厂
bootstrap.channel(NioServerSocketChannel.class);
/**
* 传入自定义客户端Handle(服务端在这里搞事情)
*/
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 注册handler
ch.pipeline().addLast(new SimpleServerHandler());
}
});
// 绑定端口,开始接收进来的连接
ChannelFuture f = bootstrap.bind(port).sync();
// 等待服务器 socket 关闭 。
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
acceptor.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) {
new ServerTest().StartNetty();
}
}
/**设置选项
* 参数:Socket的标准参数(key,value),可自行百度
* eg:
* bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
*bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
* */
ClientTest 类
package Test;
import io.netty.bootstrap.Bootstrap;
//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;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* 客户端消费者对象
* This is an netty Client
*/
public class ClientTest {
public void connect(String host, int port) throws Exception {
EventLoopGroup worker = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
/**
*EventLoop的组
*/
b.group(worker);
/**
* 用于构造socketchannel工厂
*/
b.channel(NioSocketChannel.class);
/**设置选项
* */
b.option(ChannelOption.SO_KEEPALIVE, true);
/**
* 自定义客户端Handle(客户端在这里搞事情)
*/
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleClientHandler());
}
});
/** 开启客户端监听*/
ChannelFuture f = b.connect(host, port).sync();
/**等待数据直到客户端关闭*/
f.channel().closeFuture().sync();
} finally {
worker.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
ClientTest client=new ClientTest();
// client.connect("127.0.0.1", 9999);
client.connect("192.168.172.1", 54111);
}
}