feiyu02
2025-08-14 dac47617b37ccfb834cd73ce0ee725e1101de214
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.flightfeather.uav.socket.decoder
 
import com.flightfeather.uav.common.utils.GsonUtils
import com.flightfeather.uav.socket.sender.WebSocketMessage
import org.springframework.util.StringUtils
 
object UnderwayWebSocketParser {
 
    const val START_STR: String = "##"
    const val SPLIT_STR: String = "&&"
    const val END_STR: String = "%%"
 
    /**
     * 消息格式校验
     * @param message 消息
     * @return 格式是否合规
     */
    private fun verificationMessage(message: String): Boolean {
        if (message.isEmpty()) {
            return false
        }
        if (!message.startsWith(START_STR)) {
            return false
        }
        if (!message.endsWith(END_STR)) {
            return false
        }
        return true
    }
 
    /**
     * 解析出类型和内容
     * @param message socket消息中的data字段
     * @return 解析结果,如果格式不正确则返回null
     */
    fun decodeMessage(message: String): WebSocketMessage {
        if (!verificationMessage(message)) {
            // 发挥一个不会被处理的消息
            return WebSocketMessage(-1, "")
        }
        val webSocketMessage = WebSocketMessage()
        val parts: Array<String> = message.substring(START_STR.length, message.length - END_STR.length)
            .split(SPLIT_STR.toRegex())
            .dropLastWhile { it.isEmpty() }.toTypedArray()
        webSocketMessage.type = parts[0].toInt()
        webSocketMessage.content = GsonUtils.gson.fromJson(parts[1], Any::class.java)
 
        return webSocketMessage
    }
 
    /**
     * 生成指定格式的消息字符串
     * @return 生成的消息字符串
     */
    fun encodeMessage(webSocketMessage: WebSocketMessage): String {
        return START_STR + webSocketMessage.type + SPLIT_STR +
                GsonUtils.gson.toJson(webSocketMessage.content, webSocketMessage.content?.javaClass) +
                END_STR
    }
}