一个简单的Netty服务器例子
2016-07-28 14:24
393 查看
一个服务器handler,处理业务逻辑
配置服务器的启动代码
import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; System.out.println("server received: " + byteBuf.toString(CharsetUtil.UTF_8)); ctx.write(byteBuf); } }
配置服务器的启动代码
import io.netty.bootstrap.ServerBootstrap; 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 java.io.IOException; import java.net.InetSocketAddress; public class EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public static void main(String[] args) throws Exception { int port = 60000; new EchoServer(port).start(); } public void start() throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); ChannelFuture f = b.bind().sync(); System.out.println(EchoServer.class.getSimpleName() + " started listen on " + f.channel().localAddress()); f.channel().close().sync(); } finally { group.shutdownGracefully().sync(); } } }
相关文章推荐
- ORACLE使用EXPDP和IMPDP数据泵进行导出导入的方法
- Jenkins成了趋势,你还等什么?
- linux常用命令之压缩与解压缩命令
- [iOS] 使用WebViewJavascriptBridge实现OC与JS交互
- Android音频播放器的实现
- android链接服务端数据库
- AFNetWorking请求时, “Request failed: unacceptable content-type: text/html”
- Qt 使用QPluginLoader 加载外部dll的方法笔记
- Android多行文本折叠展开效果
- 查看电脑配置指令大全
- Android项目框架升级尝鲜OkHttp
- 阿里音乐流行趋势预测大赛—浅尝辄止(二)
- 动态的创建ImageView,并设置图片自适应
- Qt之Threads和QObjects
- 使用mongodb可视化管理软件adminMongo
- 阿里音乐流行趋势预测大赛—浅尝辄止(一)
- Ztree树形控件的使用
- Git常用命令
- Qt之Threads和QObjects
- Qt之Threads和QObjects