Netty入门学习系列--helloworld服务端
Posted 精讲JAVA
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Netty入门学习系列--helloworld服务端相关的知识,希望对你有一定的参考价值。
netty服务端
结合上面几篇文章,我们大体了解了netty使用的nio的原理,但是编写一个通信,使用nio过于复杂,对于我们来说,快捷使用nio通信变得尤为重要,于是,我们的主角netty出现了,简化原生nio开发。
public class NettyServerTest {
public static void main(String [] args){
new NettyServerTest().bing();
}
private void bing(){
EventLoopGroup bossgroup = new NioEventLoopGroup();
EventLoopGroup workgroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossgroup,workgroup)
.channel(NioserverSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024).childHandler(new NettyChildHandle());
try {
ChannelFuture cf = serverBootstrap.bind(9999).sync();
cf.channel().closeFuture().sync();
} catch (InterruptedException ignored) {
} finally {
bossgroup.shutdownGracefully();
workgroup.shutdownGracefully();
}
}
private class NettyChildHandle extends ChannelInitializer<socketchannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyServerHandle());
}
}}
NettyServerHandle用来处理通信请求,最主要的是实现里面的channelRead、channelReadComplete、exceptionCaught三个方法
public class NettyServerHandle extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
byte [] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
String body = new String(bytes,"UTF-8");
System.out.println("收到来自外星的命令"+body);
String currentTime = "hello".equals(body)?"my name is netty":"No";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}}
截止目前,netty的服务端编写完成。,下一篇编写客户端,客户端相对来说较为简单
以上是关于Netty入门学习系列--helloworld服务端的主要内容,如果未能解决你的问题,请参考以下文章