Ver código fonte

upd客户端, 主动发消息,并且等待服务端返回数据

wanggaokun 1 ano atrás
pai
commit
10f240feba

+ 16 - 20
PHM-admin/phm-manage/src/main/java/com/phm/manage/controller/DataDownResultController.java

@@ -1,25 +1,28 @@
 package com.phm.manage.controller;
 
 import java.util.List;
+
 import javax.servlet.http.HttpServletResponse;
-import org.springframework.security.access.prepost.PreAuthorize;
+
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.DeleteMapping;
-import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
+
 import com.phm.common.annotation.Log;
 import com.phm.common.core.controller.BaseController;
 import com.phm.common.core.domain.AjaxResult;
+import com.phm.common.core.page.TableDataInfo;
 import com.phm.common.enums.BusinessType;
+import com.phm.common.utils.poi.ExcelUtil;
 import com.phm.manage.domain.DataDownResult;
 import com.phm.manage.service.IDataDownResultService;
-import com.phm.common.utils.poi.ExcelUtil;
-import com.phm.common.core.page.TableDataInfo;
 
 /**
  * 数据下载Controller
@@ -29,8 +32,7 @@ import com.phm.common.core.page.TableDataInfo;
  */
 @RestController
 @RequestMapping("/manage/dataDown")
-public class DataDownResultController extends BaseController
-{
+public class DataDownResultController extends BaseController {
     @Autowired
     private IDataDownResultService dataDownResultService;
 
@@ -39,8 +41,7 @@ public class DataDownResultController extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('manage:dataDown:list')")
     @GetMapping("/list")
-    public TableDataInfo list(DataDownResult dataDownResult)
-    {
+    public TableDataInfo list(DataDownResult dataDownResult) {
         startPage();
         List<DataDownResult> list = dataDownResultService.selectDataDownResultList(dataDownResult);
         return getDataTable(list);
@@ -52,8 +53,7 @@ public class DataDownResultController extends BaseController
     @PreAuthorize("@ss.hasPermi('manage:dataDown:export')")
     @Log(title = "数据下载", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
-    public void export(HttpServletResponse response, DataDownResult dataDownResult)
-    {
+    public void export(HttpServletResponse response, DataDownResult dataDownResult) {
         List<DataDownResult> list = dataDownResultService.selectDataDownResultList(dataDownResult);
         ExcelUtil<DataDownResult> util = new ExcelUtil<DataDownResult>(DataDownResult.class);
         util.exportExcel(response, list, "数据下载数据");
@@ -64,8 +64,7 @@ public class DataDownResultController extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('manage:dataDown:query')")
     @GetMapping(value = "/{id}")
-    public AjaxResult getInfo(@PathVariable("id") Long id)
-    {
+    public AjaxResult getInfo(@PathVariable("id") Long id) {
         return success(dataDownResultService.selectDataDownResultById(id));
     }
 
@@ -75,8 +74,7 @@ public class DataDownResultController extends BaseController
     @PreAuthorize("@ss.hasPermi('manage:dataDown:add')")
     @Log(title = "数据下载", businessType = BusinessType.INSERT)
     @PostMapping
-    public AjaxResult add(@RequestBody DataDownResult dataDownResult)
-    {
+    public AjaxResult add(@RequestBody DataDownResult dataDownResult) {
         return toAjax(dataDownResultService.insertDataDownResult(dataDownResult));
     }
 
@@ -86,8 +84,7 @@ public class DataDownResultController extends BaseController
     @PreAuthorize("@ss.hasPermi('manage:dataDown:edit')")
     @Log(title = "数据下载", businessType = BusinessType.UPDATE)
     @PutMapping
-    public AjaxResult edit(@RequestBody DataDownResult dataDownResult)
-    {
+    public AjaxResult edit(@RequestBody DataDownResult dataDownResult) {
         return toAjax(dataDownResultService.updateDataDownResult(dataDownResult));
     }
 
@@ -96,9 +93,8 @@ public class DataDownResultController extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('manage:dataDown:remove')")
     @Log(title = "数据下载", businessType = BusinessType.DELETE)
-	@DeleteMapping("/{ids}")
-    public AjaxResult remove(@PathVariable Long[] ids)
-    {
+    @DeleteMapping("/{ids}")
+    public AjaxResult remove(@PathVariable Long[] ids) {
         return toAjax(dataDownResultService.deleteDataDownResultByIds(ids));
     }
 }

+ 18 - 22
PHM-admin/phm-netty/src/main/java/com/phm/netty/client/NettyUdpClient.java

@@ -1,6 +1,11 @@
 package com.phm.netty.client;
 
-import com.phm.netty.client.handler.NettyUdpClientHandler;
+import java.net.InetSocketAddress;
+
+import org.springframework.stereotype.Component;
+
+import com.phm.netty.client.handler.NettyUdpClientInitialize;
+
 import io.netty.bootstrap.Bootstrap;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.Channel;
@@ -9,11 +14,7 @@ import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.DatagramPacket;
 import io.netty.channel.socket.nio.NioDatagramChannel;
-import io.netty.util.CharsetUtil;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.stereotype.Component;
-
-import java.net.InetSocketAddress;
 
 /**
  * @Description NettyUdpClient
@@ -23,27 +24,24 @@ import java.net.InetSocketAddress;
 @Slf4j
 @Component
 public class NettyUdpClient {
-    public void bind(String address, int port, String data) {
+    public void bind(String address, int port, byte[] data) {
         EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
         try {
             Bootstrap clientBootstrap = new Bootstrap();
             clientBootstrap = clientBootstrap.group(eventLoopGroup);
             clientBootstrap = clientBootstrap.channel(NioDatagramChannel.class);
             clientBootstrap = clientBootstrap.option(ChannelOption.SO_BROADCAST, true);
-            clientBootstrap = clientBootstrap.handler(new NettyUdpClientHandler());
-            Channel channel = clientBootstrap.bind(0).sync().channel();
-            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data, CharsetUtil.UTF_8), new InetSocketAddress(address, port))).sync();
+            clientBootstrap = clientBootstrap.handler(new NettyUdpClientInitialize());
+            Channel channel = clientBootstrap.bind(8989).sync().channel();
+            // 给服务端发送请求信息
+            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data), new InetSocketAddress(address, port)))
+                .sync();
             log.info("channel_id = {} ", channel.id().toString());
 
-            //  方式一:查询等待超时 单位s  等待服务端原路返回的消息,
-            //  在channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)方法中收到消息后可主动关闭channel,此处等待自然释放
+            // 方式一:查询等待超时 单位s, 超时自动关闭
             channel.closeFuture().await(10000);
-
-            //	方式二:直接等待服务端原路返回后在
-            //	channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
-            //	方法中收到消息后可主动关闭channe
-            //  若服务端没有原路返回消息或者消息未收到将会一直等待,浪费资源
-            //  channel.closeFuture().sync();
+            // 方式er:原地等候返回消息,再关闭连接
+            // channel.closeFuture().sync();
 
         } catch (Exception e) {
             log.error(e.getMessage());
@@ -53,17 +51,15 @@ public class NettyUdpClient {
         }
     }
 
-
-    //    测试
+    // 测试
     public static void main(String[] args) {
 
-        //  向网段内的所有机器广播UDP消息,这个没试过是不是这个原理
+        // 向网段内的所有机器广播UDP消息,这个没试过是不是这个原理
         // new BootNettyUdpClient().bind("255.255.255.255",9999,"I am client");
 
         // 指定某个套接字地址和发送的内容可以发送消息
         // 该方式也可以封装成一个udp的客户端的send类
-        new NettyUdpClient().bind("127.0.0.1", 9999, "I am client");
-
+        // new NettyUdpClient().bind("127.0.0.1", 9999, "I am client");
 
     }
 }

+ 9 - 4
PHM-admin/phm-netty/src/main/java/com/phm/netty/client/handler/NettyUdpClientHandler.java

@@ -2,8 +2,11 @@ package com.phm.netty.client.handler;
 
 import com.phm.netty.domain.Message;
 import com.phm.netty.enums.OrderEnum;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.channel.socket.DatagramPacket;
 import lombok.extern.slf4j.Slf4j;
 
 /**
@@ -12,12 +15,14 @@ import lombok.extern.slf4j.Slf4j;
  * @Date 2023/10/30 15:30
  */
 @Slf4j
-public class NettyUdpClientHandler extends SimpleChannelInboundHandler<byte[]> {
+public class NettyUdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
     @Override
-    protected void channelRead0(ChannelHandlerContext ctx, byte[] binaryData) throws Exception {
+    protected void channelRead0(ChannelHandlerContext ctx,DatagramPacket packet) throws Exception {
+        final ByteBuf buf = packet.content();
         try {
             log.info("channelId---:{}", ctx.channel().id().toString());
-            Message msg = Message.getMessage(binaryData);
+            byte[] bytes = ByteBufUtil.getBytes(buf);
+            Message msg = Message.getMessage(bytes);
             if (msg == null) {
                 return;
             }
@@ -26,7 +31,7 @@ public class NettyUdpClientHandler extends SimpleChannelInboundHandler<byte[]> {
             log.info("msg---:{}", msg);
             if (OrderEnum.ORDER_CONFIG.getType() != type) {
                 // 数据
-                log.info("");
+                log.info("数据数据数据");
             }
             ctx.close();
         } catch (Exception e) {

+ 21 - 0
PHM-admin/phm-netty/src/main/java/com/phm/netty/client/handler/NettyUdpClientInitialize.java

@@ -0,0 +1,21 @@
+package com.phm.netty.client.handler;
+
+import org.springframework.stereotype.Component;
+
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.socket.nio.NioDatagramChannel;
+
+/**
+ * @Description NettyClientInitialize 客户端初始类
+ * @Author WGK
+ * @Date 2023/9/15 9:21
+ */
+@Component
+public class NettyUdpClientInitialize extends ChannelInitializer<NioDatagramChannel> {
+    @Override
+    protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
+        ChannelPipeline pipeline = nioDatagramChannel.pipeline();
+        pipeline.addLast(new NettyUdpClientHandler());
+    }
+}

+ 14 - 1
PHM-admin/phm-netty/src/main/java/com/phm/netty/controller/NettyUdpClientController.java

@@ -1,9 +1,12 @@
 package com.phm.netty.controller;
 
+import com.phm.common.annotation.Anonymous;
 import com.phm.common.core.controller.BaseController;
 import com.phm.common.core.page.TableDataInfo;
 import com.phm.manage.domain.common.CommonResult;
 import com.phm.netty.client.NettyUdpClient;
+import com.phm.netty.domain.Message;
+import com.phm.netty.enums.OrderEnum;
 import com.phm.system.domain.SysConfig;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
@@ -20,15 +23,25 @@ import java.util.List;
  * @Date 2023/10/30 15:46
  */
 @RestController
+@Anonymous
 @RequestMapping("/udp")
 public class NettyUdpClientController extends BaseController {
     @Autowired
     private NettyUdpClient udpClient;
 
     @PostMapping("/getInfo")
-    public CommonResult<String> getInfo(SysConfig config) {
+    public CommonResult<String> getInfo() {
         // udp客户端,向服务端发送获取数据请求服务
         udpClient.bind("", 0, null);
         return CommonResult.buildSuccess();
     }
+
+    @PostMapping("/getInfo2")
+    public CommonResult<String> getInfo2() {
+        Message message = new Message();
+        message.setType(OrderEnum.ORDER_CONFIG.getType()).setTarget("GPHM").setSource("SPHM").setData("{\"cmdId\": \"getConfig\"}");
+        // udp客户端,向服务端发送获取数据请求服务
+        udpClient.bind("127.0.0.1", 19000, Message.msgToBytes(message));
+        return CommonResult.buildSuccess();
+    }
 }