import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* Netty 服務端
*/
public class NettyServerListenerSimple {
/**
* 創建bootstrap
*/
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
/**
* Worker
*/
private static final EventLoopGroup work = new NioEventLoopGroup();
/**
* 端口號
*/
private int port = getPort();
/**
* 關閉服務器方法
*/
public void close() {
System.out.println("關閉服務器....");
//優雅退出
work.shutdownGracefully();
}
/**
* 開啓及服務線程
*/
public void start() {
serverBootstrap.group(work)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO));
try {
//設置事件處理
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ServerChannelHandlerSimple());
}
});
System.out.println("netty服務器在[" + port + "]端口啓動監聽");
ChannelFuture f = serverBootstrap.bind(port);
f.channel().closeFuture();
} catch (Exception e) {
System.out.println("[出現異常] 釋放資源");
} finally {
close();
}
}
private static int getPort() {
Double port = (Math.random() + 1) * 10000;
return port.intValue();
}
public static void main(String[] args) {
NettyServerListenerSimple nsl = new NettyServerListenerSimple();
nsl.start();
}
}
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20191122143044930.png)
```cpp
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.nio.charset.Charset;
/**
* 服務端的通道適配器
*/
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("error.");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 具體處理客戶端的數據信息
System.out.println("receive message. ");
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
System.out.println(rev);
// 如果有多個適配器,調用此方法通知下一個適配器執行,並將處理過的數據傳遞給下一個適配器
ctx.fireChannelRead(rev);
}
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, Charset.forName("GBK"));
} catch (Exception e) {
System.out.println("trans bytes to string error. ");
e.printStackTrace();
return null;
}
}
}
Channel、ChannelHandler
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.