国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 幫助中心 > 正文

通過入門demo簡單了解netty使用方法

2024-07-09 22:42:19
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了通過入門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();  }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 中牟县| 综艺| 盐亭县| 舟曲县| 普格县| 长武县| 孝昌县| 隆昌县| 乌海市| 囊谦县| 泗阳县| 广州市| 隆德县| 巨野县| 赫章县| 裕民县| 金塔县| 子洲县| 福贡县| 翁源县| 乳山市| 吴江市| 卢湾区| 高碑店市| 通渭县| 伊春市| 陇川县| 繁峙县| 巩义市| 高青县| 新竹市| 攀枝花市| 临西县| 长治市| 开化县| 集贤县| 岢岚县| 奉贤区| 独山县| 开远市| 浦江县|