无论服务器还是客户端都是由下面两步组成
1、ChannelHandler 用与处理各种事件的逻辑处理。
决定了连接创建后和接收到信息后该如何处理。
直接或简接要实现ChannelInboundHandler 接口.
2、Bootstrap启动服务器或客户端 服务器用 ServerBootstrap 客户端用 BootStrap。
pom
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.29.Final</version> </dependency> |
EchoServerChannelHandler
package
test01;
import
io.netty.buffer.ByteBuf;
import
io.netty.buffer.Unpooled;
import
io.netty.channel.ChannelFutureListener;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.channel.ChannelInboundHandlerAdapter;
import
io.netty.util.CharsetUtil;
/**
* Created by wujiazhen on 2018/1/15.
*/
public class
EchoServerChannelHandler
extends
ChannelInboundHandlerAdapter {
@Override
public void
channelRead(ChannelHandlerContext ctx, Object msg)
throws
Exception {
ByteBuf in = (ByteBuf)msg;
System.
out
.println(
"server receive:"
+in.toString(CharsetUtil.
UTF_8
));
ctx.write(msg);
}
@Override
public void
channelReadComplete(ChannelHandlerContext ctx)
throws
Exception {
ctx.writeAndFlush(Unpooled.
EMPTY_BUFFER
)
.addListener(ChannelFutureListener.
CLOSE
);
}
@Override
public void
exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws
Exception {
cause.printStackTrace();
//5
ctx.close();
}
}
|
服务器启动
package
test01;
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
java.net.InetSocketAddress;
import
java.util.concurrent.TimeUnit;
/**
* Created by wujiazhen on 2018/1/15.
*/
public class
EchoServer {
private int
port
;
public
EchoServer(){};
public
EchoServer(
int
port){
this
.
port
=port;
}
public static void
main(String args[]){
new
EchoServer(
2000
).start();
}
public void
start() {
NioEventLoopGroup group =
new
NioEventLoopGroup();
try
{
/*
1.创建 EventLoopGroup
2.创建 ServerBootstrap
3.指定使用 NIO 的传输 Channel
4.设置 socket 地址使用所选的端口
5.添加 EchoServerHandler 到 Channel 的 ChannelPipeline
*/
ServerBootstrap bootstrap =
new
ServerBootstrap()
.channel(NioServerSocketChannel.
class
)
.group(group)
.localAddress(
new
InetSocketAddress(
this
.getPort()))
.childHandler(
new
ChannelInitializer<SocketChannel>() {
public void
initChannel(SocketChannel socketChannel)
throws
Exception {
/*
ChannelInitializer 。当一个新的连接被接受,一个新的子 Channel 将被创建,
ChannelInitializer 会添加我们EchoServerHandler 的实例到 Channel 的 ChannelPipeline。
正如我们如前所述,如果有入站信息,这个处理器将被通知。
*/
socketChannel.pipeline().addLast(
new
EchoServerChannelHandler());
}
});
// 6.绑定的服务器;sync 等待服务器关闭
ChannelFuture future = bootstrap.bind().sync();
System.
out
.println(EchoServer.
class
.getName() +
" started and listen on "
+ future.channel().localAddress());
//7.关闭 channel 和 块,直到它被关闭
future.channel().closeFuture().sync();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
finally
{
try
{
group.shutdownGracefully().sync();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
public int
getPort() {
return
port
;
}
public void
setPort(
int
port) {
this
.
port
= port;
}
}
|
客户端handler
package
test01;
import
io.netty.buffer.ByteBuf;
import
io.netty.buffer.Unpooled;
import
io.netty.channel.ChannelHandlerContext;
import
io.netty.channel.SimpleChannelInboundHandler;
import
io.netty.util.CharsetUtil;
/**
* Created by wujiazhen on 2018/1/15.
*/
public class
EchoClientChannelHandler
extends
SimpleChannelInboundHandler {
protected void
channelRead0(ChannelHandlerContext channelHandlerContext, Object msg)
throws
Exception {
ByteBuf in = (ByteBuf)msg;
System.
out
.println(
"client receive:"
+in.toString(CharsetUtil.
UTF_8
));
}
@Override
public void
channelActive(ChannelHandlerContext ctx)
throws
Exception {
System.
out
.println(
"connect success"
);
ctx.writeAndFlush(Unpooled.
copiedBuffer
(
"客户端:建立....."
,CharsetUtil.
UTF_8
));
super
.channelActive(ctx);
}
}
|
客户端启动
package
test01;
import
io.netty.bootstrap.Bootstrap;
import
io.netty.channel.ChannelFuture;
import
io.netty.channel.ChannelInitializer;
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;
/**
* Created by wujiazhen on 2018/1/15.
*/
public class
EchoClient {
public static void
main(String[] args){
new
EchoClient().start();
}
public void
start(){
NioEventLoopGroup group =
new
NioEventLoopGroup();
try
{
Bootstrap bootstrap =
new
Bootstrap();
bootstrap.group(group)
//区别与服务端的channel,客户端用NioSocketChannel
.channel(NioSocketChannel.
class
)
.remoteAddress(
"127.0.0.1"
,
2000
)
.handler(
new
ChannelInitializer<SocketChannel>() {
protected void
initChannel(SocketChannel socketChannel)
throws
Exception {
socketChannel.pipeline().addLast(
new
EchoClientChannelHandler
());
}
});
ChannelFuture sync = bootstrap.connect().sync();
sync.channel().closeFuture().sync();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
finally
{
try
{
group.shutdownGracefully().sync();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
}
|