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
|
}
|
}
|