Selaa lähdekoodia

调整拓扑索尔推送数据同步模块逻辑

james 1 viikko sitten
vanhempi
commit
50dea12bdf

+ 31 - 12
agbox-topsail/src/main/java/com/usky/topsail/service/impl/SpSj2017ServiceImpl.java

@@ -15,6 +15,7 @@ import com.usky.topsail.service.SpSj2017Service;
 import com.usky.common.mybatis.core.AbstractCrudService;
 import com.usky.topsail.service.config.mqtt.MqttOutConfig;
 import com.usky.topsail.service.util.HttpClientUtil;
+import com.usky.topsail.service.util.TcpRawDataSender;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpMethod;
@@ -159,10 +160,14 @@ public class SpSj2017ServiceImpl extends AbstractCrudService<SpSj2017Mapper, SpS
                         String httpOrgCreateTestRtn = HttpClientUtil.doPost(httpurl, map, "utf-8");
 
                         //增加水表数据推送总队逻辑
-                        String data = "SubType=2&DeviceId="+device_code+"&InsertId="+String.valueOf(insertid1)+"&Confirmed="+"false";
+                        String serverIp = "47.98.201.187";
+                        int serverPort = 55335;
 
-                        String response = HttpClientUtil.doPost1("47.98.201.187", 55335, "/report", data, "utf-8");
-                        System.out.println("http://47.98.201.187:55335/report response:"+response);
+                        // 示例1:使用默认配置发送
+                        System.out.println("=== 示例1:默认配置发送 ===");
+                        String reqData = "{\"SubType\":2,\"DeviceId\":\""+device_code+"\",\"InsertId\":"+ insertid1 +",\"Confirmed\":false}";
+                        String response1 = TcpRawDataSender.sendTcpData(serverIp, serverPort, reqData);
+                        System.out.println("示例1响应结果:" + response1);
                     }else if (alarm.equals("262144")){
                         device_status = "WP2";
                         dbMap3.put("value","2");
@@ -200,10 +205,16 @@ public class SpSj2017ServiceImpl extends AbstractCrudService<SpSj2017Mapper, SpS
                         String httpOrgCreateTestRtn = HttpClientUtil.doPost(httpurl, map, "utf-8");
 
                         //增加水表数据推送总队逻辑
-                        String data = "SubType=2&DeviceId="+device_code+"&InsertId="+String.valueOf(insertid1)+"&Confirmed="+"false";
+                        String serverIp = "47.98.201.187";
+                        int serverPort = 55335;
 
-                        String response = HttpClientUtil.doPost1("47.98.201.187", 55335, "/report", data, "utf-8");
-                        System.out.println("http://47.98.201.187:55335/report response:"+response);
+                        // 示例1:使用默认配置发送
+                        System.out.println("=== 示例1:默认配置发送 ===");
+                        String reqData = "{\"SubType\":2,\"DeviceId\":\""+device_code+"\",\"InsertId\":"+ insertid1 +",\"Confirmed\":false}";
+                        String response1 = TcpRawDataSender.sendTcpData(serverIp, serverPort, reqData);
+                        System.out.println("示例1响应结果:" + response1);
+
+                        
                     }
                     db.add(dbMap3);
                 }else if (dev_type.equals(2)){
@@ -257,10 +268,14 @@ public class SpSj2017ServiceImpl extends AbstractCrudService<SpSj2017Mapper, SpS
                         String httpOrgCreateTestRtn = HttpClientUtil.doPost(httpurl, map, "utf-8");
 
                         //增加水表数据推送总队逻辑
-                        String data = "SubType=5&DeviceId="+device_code+"&InsertId="+String.valueOf(insertid1)+"&Confirmed="+"false";
+                        String serverIp = "47.98.201.187";
+                        int serverPort = 55335;
 
-                        String response = HttpClientUtil.doPost1("47.98.201.187", 55335, "/report", data, "utf-8");
-                        System.out.println("http://47.98.201.187:55335/report response:"+response);
+                        // 示例1:使用默认配置发送
+                        System.out.println("=== 示例1:默认配置发送 ===");
+                        String reqData = "{\"SubType\":5,\"DeviceId\":\""+device_code+"\",\"InsertId\":"+ insertid1 +",\"Confirmed\":false}";
+                        String response1 = TcpRawDataSender.sendTcpData(serverIp, serverPort, reqData);
+                        System.out.println("示例1响应结果:" + response1);
                     }else if (alarm.equals("262144")){
                         payloadVO1.put("type","ALARM");
                         dbMap3.put("value","2");
@@ -298,10 +313,14 @@ public class SpSj2017ServiceImpl extends AbstractCrudService<SpSj2017Mapper, SpS
                         String httpOrgCreateTestRtn = HttpClientUtil.doPost(httpurl, map, "utf-8");
 
                         //增加水表数据推送总队逻辑
-                        String data = "SubType=5&DeviceId="+device_code+"&InsertId="+String.valueOf(insertid1)+"&Confirmed="+"false";
+                        String serverIp = "47.98.201.187";
+                        int serverPort = 55335;
 
-                        String response = HttpClientUtil.doPost1("47.98.201.187", 55335, "/report", data, "utf-8");
-                        System.out.println("http://47.98.201.187:55335/report response:"+response);
+                        // 示例1:使用默认配置发送
+                        System.out.println("=== 示例1:默认配置发送 ===");
+                        String reqData = "{\"SubType\":5,\"DeviceId\":\""+device_code+"\",\"InsertId\":"+ insertid1 +",\"Confirmed\":false}";
+                        String response1 = TcpRawDataSender.sendTcpData(serverIp, serverPort, reqData);
+                        System.out.println("示例1响应结果:" + response1);
                     }
                     db.add(dbMap3);
                 }

+ 1 - 51
agbox-topsail/src/main/java/com/usky/topsail/service/util/HttpClientUtil.java

@@ -7,6 +7,7 @@ import org.apache.http.NameValuePair;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.util.EntityUtils;
 import org.springframework.stereotype.Repository;
@@ -52,55 +53,4 @@ public class HttpClientUtil {
         return result;
     }
 
-    public static String doPost1(String destIp, int destPort, String destPath, String data,  String charset) {
-        HttpClient httpClient = null;
-        HttpPost httpPost = null;
-        String result = null;
-        String httpUrl = String.format("http://%s:%d%s", destIp, destPort, destPath);
-        try {
-            httpClient = new SSLClient();
-            httpPost = new HttpPost(httpUrl);
-
-            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
-            httpPost.addHeader("Accept", "*/*");
-            httpPost.addHeader("Connection", "keep-alive");
-            httpPost.addHeader("Cache-Control", "no-cache");
-            httpPost.addHeader("Accept-Encoding", "gzip");
-            httpPost.addHeader("Accept-Language", "zh-CN,en,*");
-            httpPost.addHeader("User-Agent", "Mozilla/5.0");
-            httpPost.addHeader("Host", String.format("%s:%d", destIp, destPort));
-            // 手动设置 Content-Length(和 Qt 的 arg(data.length()) 完全一致)
-            httpPost.addHeader("Content-Length", String.valueOf(data.getBytes(StandardCharsets.UTF_8).length));
-            //设置参数
-            // 3. 解析表单参数(对应 Qt 的 %5 占位符)
-            if (data != null && !data.isEmpty()) {
-                List<BasicNameValuePair> params = new ArrayList<>();
-                String[] keyValuePairs = data.split("&");
-                for (String pair : keyValuePairs) {
-                    String[] keyValue = pair.split("=");
-                    if (keyValue.length == 2) {
-                        // URL 解码(处理中文/特殊字符,和 Qt 编码逻辑一致)
-                        String key = URLDecoder.decode(keyValue[0], charset);
-                        String value = URLDecoder.decode(keyValue[1], charset);
-                        params.add(new BasicNameValuePair(key, value));
-                    }
-                }
-                // 封装表单参数(application/x-www-form-urlencoded 格式)
-                httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
-            }
-            HttpResponse response = httpClient.execute(httpPost);
-            System.out.println("HttpPost1 +++++++++++++++ " + httpUrl);
-            if (response != null) {
-                HttpEntity resEntity = response.getEntity();
-                if (resEntity != null) {
-                    result = EntityUtils.toString(resEntity, charset);
-                }
-            }
-        } catch (Exception ex) {
-            ex.printStackTrace();
-        }
-        return result;
-    }
-
-
 }

+ 107 - 0
agbox-topsail/src/main/java/com/usky/topsail/service/util/TcpRawDataSender.java

@@ -0,0 +1,107 @@
+package com.usky.topsail.service.util;
+
+import java.io.*;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Java Socket 发送 TCP 裸数据示例
+ * 功能:建立 TCP 连接 → 发送原始数据 → 接收响应 → 关闭连接
+ * 特点:支持自定义超时、编码、结束符,适合与非 HTTP 协议的服务器通信
+ */
+public class TcpRawDataSender{
+
+    /**
+     * 发送 TCP 裸数据的核心方法
+     * @param serverIp 服务器IP地址(如 "47.98.201.187")
+     * @param serverPort 服务器端口(如 55335)
+     * @param data 要发送的原始数据(如 "deviceId=DEV001&value=220")
+     * @param charset 字符编码(推荐 StandardCharsets.UTF_8)
+     * @param timeout 超时时间(毫秒,0表示不超时)
+     * @param endMarker 数据结束标记(如 "\r\n",null表示不添加)
+     * @return 服务器返回的响应数据(null表示无响应或失败)
+     */
+    public static String sendTcpData(String serverIp, int serverPort, String data,
+                                     String charset, int timeout, String endMarker) {
+        Socket socket = null;
+        OutputStream outputStream = null;
+        InputStream inputStream = null;
+        BufferedReader reader = null;
+
+        try {
+            // 1. 建立 TCP 连接
+            socket = new Socket(serverIp, serverPort);
+            System.out.println("已建立 TCP 连接:" + serverIp + ":" + serverPort);
+
+            // 2. 配置连接参数
+            if (timeout > 0) {
+                socket.setSoTimeout(timeout); // 设置读取超时
+            }
+            socket.setTcpNoDelay(true); // 禁用 Nagle 算法,立即发送数据(不缓冲)
+
+            // 3. 处理要发送的数据(添加结束标记)
+            String dataToSend = data;
+            if (endMarker != null && !endMarker.isEmpty()) {
+                dataToSend += endMarker; // 拼接结束符(如 "\r\n",根据服务器要求调整)
+            }
+            byte[] sendBytes = dataToSend.getBytes(charset); // 按指定编码转换为字节
+            System.out.println("待发送数据(编码:" + charset + "):" + dataToSend);
+            System.out.println("发送字节数:" + sendBytes.length);
+
+            // 4. 发送数据
+            outputStream = socket.getOutputStream();
+            outputStream.write(sendBytes);
+            outputStream.flush(); // 强制发送缓冲区数据
+            System.out.println("数据发送完成");
+
+            // 5. 接收服务器响应(按行读取,适合文本协议)
+            inputStream = socket.getInputStream();
+            reader = new BufferedReader(new InputStreamReader(inputStream, charset));
+
+            // 读取响应(根据服务器协议调整:单行/多行/固定长度)
+            StringBuilder response = new StringBuilder();
+            String line;
+            while ((line = reader.readLine()) != null) { // 读取一行(以换行符为结束)
+                response.append(line);
+                // 若服务器返回单行响应,可在此处 break
+                // break;
+            }
+
+            String responseData = response.toString();
+            System.out.println("收到服务器响应:" + (responseData.isEmpty() ? "(空响应)" : responseData));
+            return responseData;
+
+        } catch (IOException e) {
+            System.err.println("TCP 通信异常:" + e.getMessage());
+            e.printStackTrace();
+            return null;
+        } finally {
+            // 6. 关闭所有资源(避免连接泄漏)
+            try {
+                if (reader != null) reader.close();
+                if (inputStream != null) inputStream.close();
+                if (outputStream != null) outputStream.close();
+                if (socket != null) socket.close();
+                System.out.println("TCP 连接已关闭");
+            } catch (IOException e) {
+                System.err.println("关闭资源失败:" + e.getMessage());
+            }
+        }
+    }
+
+    /**
+     * 简化调用的重载方法(默认配置:UTF-8编码、30秒超时、无结束符)
+     */
+    public static String sendTcpData(String serverIp, int serverPort, String data) {
+        return sendTcpData(
+                serverIp,
+                serverPort,
+                data,
+                StandardCharsets.UTF_8.name(), // 默认UTF-8编码
+                30000, // 默认30秒超时
+                null // 默认不添加结束符
+        );
+    }
+
+
+}