博客
关于我
Netty4服务端入门代码示例
阅读量:348 次
发布时间:2019-03-04

本文共 2694 字,大约阅读时间需要 8 分钟。

??Maven?????Netty???

??????Netty??????Netty???????????????????pom.xml??????????????????Netty??????

?????

import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.Channel;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;public class NetttyServer {    public static void main(String[] args) {        EventLoopGroup boss = new NioEventLoopGroup();        EventLoopGroup worker = new NioEventLoopGroup();        ServerBootstrap bootstrap = new ServerBootstrap();        bootstrap.group(boss, worker)                .channel(NioServerSocketChannel.class)                .childHandler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline() .addLast("encoder", new StringEncoder()) .addLast("decoder", new StringDecoder()) .addLast("hello world handler", new HelloWorldHandler()); } }); try { ChannelFuture channelFuture = bootstrap.bind(8080).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } static class HelloWorldHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channel Active and write back......"); String resp = "Hello world"; ChannelFuture future = ctx.channel().writeAndFlush(resp); future.sync(); System.out.println("success:" + future.isSuccess()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("read msg : " + msg); String resp = "Hello world"; ctx.channel().writeAndFlush(resp); } }}

?????????Netty????????????????????????

io.netty
netty-all
4.1.36.Final

??????????????????????NioEventLoopGroup??????????NioServerSocketChannel??????????Pipeline????????????????????HelloWorldHandler??????

?????????????????????8080????????????????????????????"Hello world"???????????????????????

???????????????????Netty????????????????

转载地址:http://qume.baihongyu.com/

你可能感兴趣的文章
Objective-C实现高精度乘法(附完整源码)
查看>>
Objective-C实现高精度减法(附完整源码)
查看>>
Objective-C实现高精度除法(附完整源码)
查看>>
Objective-C实现鸡兔同笼问题(附完整源码)
查看>>
Objective-c正确的写法单身
查看>>
Objective-C语法之代码块(block)的使用
查看>>
ObjectMapper - 实现复杂类型对象反序列化(天坑!)
查看>>
ObjectProperty 类的使用
查看>>
Objects.equals有坑
查看>>
Object常用方法
查看>>
Object方法的finalize方法
查看>>
Object类有哪些方法,hashcode方法的作用,为什么要重写hashcode方法?
查看>>
Objenesis创建类的实例
查看>>
OBObjective-c 多线程(锁机制) 解决资源抢夺问题
查看>>
OBS studio最新版配置鉴权推流
查看>>
Obsidian的使用-ChatGPT4o作答
查看>>
Obsidian笔记记录GPT回复的数学公式无缝转化插件Katex to mathjax
查看>>
ObsoleteAttribute 可适用于除程序集、模块、参数或返回值以外的所有程序元素。 将元素标记为过时可以通知用户:该元素在产品的未来版本中将被移除。...
查看>>
OC block声明和使用
查看>>
OC Xcode快捷键
查看>>