Socket.D
是基於"事件"和"語義消息""流"的網絡應用層協議。有用戶說,“Socket.D 之於 Socket,尤如 Vue 之於 Js、Mvc 之於 Http”。支持 tcp, udp, ws, kcp 傳輸。協議特點可參考《官網介紹》。
Socket.D.js 兼容更新說明
是近期發佈的 socket.d 協議 js client 實現。經過社區的努力,現已:
- 兼容 h5(瀏覽器)
- 兼容 uniapp(瀏覽器、android, ios)
- 兼容 微信小程序(wx 接口)
- 兼容 node.js
Socket.D.js 能力演示:
- 監聽(相當於 ws 的增強)
多了事件路由。可以用一個連接,監聽不同的業務事件(類似於 http path)。
//打開客戶端會話(用 url 形式打開)
let session = await SocketD.createClient("sd:ws://127.0.0.1:8602/?token=1b0VsGusEkddgr3d")
.listen(SocketD.newEventListener()
.doOnOpen(s -> { //會話打開時
//...
}).doOnMessage((s, m) -> { //收到任意消息時
//打印
console.info(m);
}).doOn("/demo", (s, m) -> { //收到"/demo"事件的消息時
if (m.isRequest() || m.isSubscribe()) {
//答覆
s.replyEnd(m, SocketD.newEntity("And you too."));
}
}))
.open();
- 發送 和 發送文件(並獲取進度)
發送相對於 ws 多了元信息。可爲數據添加額外的業務標註。發送大數據時,會自動分片(接收端自動聚合)
//發送
session.send("/demo/hello", SocketD.newEntity("hi").metaPut("sender","noear"));
//發送文件,且獲取發送進度(如果有大數據發送,又需要顯示進度)//實際開發,要用 sendAndRequest 接口(以獲取接收確認)
session.send("/demo/upload", SocketD.newEntity(file)).thenProgress((isSend, val, max)=>{
if(isSend){
//獲取發送進度
console.info(`...${val}/${max}`);
}
});
- 請求 和 下載文件(或大數據塊)
這個相當於 ws 有了 ajax 的交互方式
//發送並請求(有點像 ajax)
let reply = session.sendAndRequest("/demo/hello", SocketD.newEntity()).thenReply(reply=>{
console.info(reply.dataAsString());
});
//發送並請求,且取接收進度(如果有大數據獲取,又需要顯示進度)
session.sendAndRequest("/demo/download", SocketD.newEntity()).thenProgress((isSend, val, max)=>{
if(!isSend){
//獲取接收進度
console.info(`...${val}/${max}`);
}
}).thenReply(reply=>{
//reply.data()...
}).thenError(err=>{
//如果有出錯?
});
- 訂閱 與 流量控制(一般用於流加載)
通過 range(start, size) 指定數據範圍,由 sendAndSubscribe 發起訂閱,通過 thenReply 多次接收。
//發送並訂閱
let entity = SocketD.newEntity().range(5,5).metaPut("videoId","1");
session.sendAndSubscribe("/demo/stream", entity).thenReply(reply=>{
//異步獲取答覆(會多次回調)
})
視頻演示效果:
- for H5
- for UniAPP