這篇文章主要介紹了通過入門demo簡單了解netty使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
前言
最近做一個項目:
大概需求: 多個溫度傳感器不斷向java服務發送溫度數據,該傳感器采用socket發送數據;該數據以$符號開頭和結尾,最后將處理的數據存入數據庫;
我想到的處理方式:采用netty來接收和處理數據,然后用mybatis將處理后的數據存入數據庫;
我在這之前從來沒使用過netty,在網上倒是看到不少關于netty的文章,如今就趁著這個項目寫一下我所學到的東西和遇到的問題,又是怎么去解決的;
接下來的幾篇文章都是圍繞著這個項目來寫的;本篇主要寫netty的入門demo;
正文
代碼部分
新建一個maven項目
首先在pom.xml中導入:
<!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha1</version> </dependency>
服務端
1. DiscardServer類,netty的服務端
public class DiscardServer { public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); System.out.println("準備運行端口:" + port); try { ServerBootstrap b = new ServerBootstrap(); b = b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childHandler(new ChildChannelHandler()); //綁定端口,同步等待成功 ChannelFuture f = b.bind(port).sync(); //等待服務監聽端口關閉 f.channel().closeFuture().sync(); } finally { //退出,釋放線程資源 workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { new DiscardServer().run(8080); }}
2. ChildChannelHandler類:
public class ChildChannelHandler extends ChannelInitializer<SocketChannel> { protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new DiscardServerHandler()); }}
3. DiscardServerHandler類
在這里是繼承的ChannelHandlerAdapter類,當然還可以繼承其他的類,例如SimpleChannelInboundHandler,ChannelInboundHandlerAdapter都可以
public class DiscardServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { ByteBuf in = (ByteBuf) msg; System.out.println("傳輸內容是"); System.out.println(in.toString(CharsetUtil.UTF_8)); ByteBuf resp= Unpooled.copiedBuffer("收到信息$".getBytes()); ctx.writeAndFlush(resp); } finally { ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 出現異常就關閉 cause.printStackTrace(); ctx.close(); }}
新聞熱點
疑難解答