Socket.D 替代 Http 協議像 Ajax 一樣開發前端接口

我們在"前端接口"開發時,使用 socket.d 協議有什麼好處:

  • 功能上可以替代 http 和原生 ws
  • 更安全!現有的工具想抓包數據,難!難!難!(socket.d 是個新的二進制協議)

1、Socket.D 協議特點

  • 基於事件,每個消息都可事件路由
  • 所謂語義,通過元信息進行語義描述
  • 流關聯性,有相關的消息會串成一個流
  • 語言無關,使用二進制輸傳數據(支持 tcp, ws, udp)。支持多語言、多平臺
  • 斷線重連,自動連接恢復
  • 多路複用,一個連接便可允許多個請求和響應消息同時運行
  • 雙向通訊,單鏈接雙向互聽互發
  • 自動分片,數據超出 16Mb(大小可配置),會自動分片、自動重組(udp 除外)
  • 接口簡單,是響應式但用回調接口

2、客戶端示例代碼

使用時,可以根據自己的業務對原生接口包裝,進一步簡化使用。

<script src="js/socket.d.js"></script>
<script>
//創建單例
const clientSession = SocketD.createClient("sd:ws://127.0.0.1:8602/?u=a&p=2")
        .open();

//添加用戶(加個內容類型,方便與 Mvc 對接)
const entity = SocketD.newEntity("{id:1,name:'noear'}").metaPut("Content-Type","text/json"),
clientSession.sendAndRequest("/user/add",  entity, reply=>{
    const rst = JSON.parse(reply.dataAsString());
    
    if(rst.code == 200){
        alert("添加成功!");
    }else{
        alert("添加失敗");
    }
})
</script>

Socket.D 有三個發消息的接口:

接口 說明
send 像 websocket。多了事件與元信息屬性
sendAndRequest 像 http
sendAndSubscribe 像 reactive stream 。多了事件與元信息屬性

3、服務端示例代碼

  • 原生接口風格
public class Demo {
    public static void main(String[] args) throws Throwable {
        //創建監聽器
        Listener listener = new EventListener().doOnOpen(s->{
            //鑑權
            if("a".equals(s.param("u")) == false){
                s.close();
            }
        }).doOn("/user/add", (s,m)->{
            if(m.isRequest()){
                s.reply(m, new StringEntity("{\"code\":200}"));
            }
        });
        
        //啓動服務
        SocketD.createServer("sd:ws")
                .config(c -> c.port(8602))
                .listen(listener)
                .start();
    }
}
  • Mvc 接口風格

具體參考 solon 的集成效果:https://solon.noear.org/article/652

//控制器
@Controller
public class HelloController {
    @Socket
    @Mapping("/hello/add")
    public Result hello(long id, String name) { //{code:200,...}
        return Result.succeed();
    }
}

4、開源倉庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章