來源:小虎哥的技術(shù)博客 發(fā)布時間:2018-11-21 15:48:28 閱讀量:1063
Netty提供異步的、事件驅(qū)動的網(wǎng)絡(luò)應(yīng)用程序框架和工具,用以快速開發(fā)高性能、高可靠性的網(wǎng)絡(luò)服務(wù)器和客戶端程序,阿里騰訊都有用到,這里是個簡單的服務(wù)器和客戶端的例子
代碼目錄
服務(wù)端 NettyServerBootstrap類 NettyServerHandler類
客戶端NettyClient類 NettyClientHandler類
服務(wù)端
NettyServerBootstrap 類,建立服務(wù)端
public class NettyServerBootstrap {
private int port;
public NettyServerBootstrap(int port) {
this.port = port;
bind();
}
private void bind() {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline p = socketChannel.pipeline();
p.addLast(new NettyServerHandler());
}
});
ChannelFuture f = bootstrap.bind(port).sync();
if (f.isSuccess()) {
Log.logD("啟動Netty服務(wù)成功,端口號:" + this.port);
}
// 關(guān)閉連接
f.channel().closeFuture().sync();
} catch (Exception e) {
Log.logE("啟動Netty服務(wù)異常,異常信息:" + e.getMessage());
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
NettyServerBootstrap server = new NettyServerBootstrap(6666);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
服務(wù)端處理類NettyServerHandler
public class NettyServerHandler extends ChannelHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
//發(fā)送信息
ctx.writeAndFlush(getSendByteBuf("服務(wù)器-->客戶端 你好"));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//收到消息
ByteBuf buf = (ByteBuf) msg;// 獲取客戶端傳來的Msg
String recieved = getMessage(buf);
System.out.println("------收到信息------"+recieved );
}
/*
* 從ByteBuf中獲取信息 使用UTF-8編碼返回
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, utils.Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/*
* 將Sting轉(zhuǎn)化為UTF-8編碼的字節(jié)
*/
private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException {
byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);
return pingMessage;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
客戶端
NettyClient類
public class NettyClient {
private int port;
private String host;
private SocketChannel socketChannel;
public NettyClient(int port, String host) throws InterruptedException {
this.port = port;
this.host = host;
start();
}
private void start() throws InterruptedException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.group(eventLoopGroup);
bootstrap.remoteAddress(host, port);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyClientHandler());
socketChannel.pipeline().addLast(new HeartLinkHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
System.out.println("------connect server success------");
}
future.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
NettyClient client = new NettyClient(6666, "localhost");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
客戶端處理類NettyClientHandler
public class NettyClientHandler extends ChannelHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
//發(fā)送信息
ctx.writeAndFlush(getSendByteBuf("客戶端-->服務(wù)端 你好"));
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// TODO Auto-generated method stub
ByteBuf buf = (ByteBuf) msg;// 獲取服務(wù)端傳來的Msg
String recieved = getMessage(buf);
System.out.println("------收到信息------"+recieved );
}
/*
* 將字節(jié)UTF-8編碼返回字符串
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, utils.Constant.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/*
* 將Sting轉(zhuǎn)化為UTF-8編碼的字節(jié)
*/
private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException {
byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);
return pingMessage;
}
}
---------------------