首页 > 编程语言 >Socket.D v2.3.9 发布(增加 node.js server 实现)

Socket.D v2.3.9 发布(增加 node.js server 实现)

时间:2024-01-31 17:35:40浏览次数:35  
标签:node Socket newEntity demo SocketD v2.3 js let reply

Socket.D

是基于"事件"和"语义消息""流"的网络应用层传输协议。有用户说,“Socket.D 之于 Socket,尤如 Vue 之于 Js、Mvc 之于 Http”。支持 tcp, udp, ws, kcp 传输。协议特点可参考《官网介绍》

pyton 已开发完成,再在测试中;go, rust, c++ 正在开发中。

for Java 适配框架更新说明:

  • 添加 CLOSE28_OPEN_FAIL 关闭码,优化关闭处理
  • 调整 SocketD.createXxx 的异常提示,带上协议架构信息
  • 调整 PathListener::of 更名为 doOf,并添加 of 函数(应用不同)

for JavaScript 适配框架更新说明:

  • 完成 for Node.js server 实现!!!
  • 添加 Session::remoteAddress,localAddress 方法
  • 添加 CLOSE28_OPEN_FAIL 关闭码,优化关闭处理
  • 调整 SocketD.createXxx 的异常提示,带上协议架构信息
  • 调整 PathListener::of 更名为 doOf,并添加 of 函数(应用不同)

新增的接口体验(for Node.js Server):

现在服务端可以用 java 也可以用 node.js(很快也可以用 python 了) 。for Node.js Server Demo:

  • 包配置
{
  "name": "demo",
  "description": "socket.d for node.js demo",
  "author": "noear",
  "dependencies": {
    "@noear/socket.d": "2.3.9",
    "ws": "^8.16.0"
  }
}
  • 服务端示例代码
const {SocketD}  = require('@noear/socket.d');

function main(){
   let server = SocketD.createServer("sd:ws")
       .config(c => c.port(8602).fragmentSize(1024 * 1024))
       .listen(buildListener())
       .start();
}

function buildListener() {
    return SocketD.newEventListener()
        .doOnOpen(s => {
            console.info("onOpen: " + s.sessionId());
        }).doOnMessage((s, m) => {
            console.info("onMessage: " + m);
        }).doOn("/demo", (s, m) => {
            if (m.isRequest()) {
                s.reply(m, SocketD.newEntity("me to!"));
            }

            if (m.isSubscribe()) {
                let size = m.rangeSize();
                for (let i = 1; i <= size; i++ ) {
                    s.reply(m, SocketD.newEntity("me to-" + i));
                }
                s.replyEnd(m, SocketD.newEntity("welcome to my home!"));
            }
        }).doOn("/upload", (s, m) => {
            if (m.isRequest()) {
                let fileName = m.meta(SocketD.EntityMetas.META_DATA_DISPOSITION_FILENAME);
                if (fileName) {
                    s.reply(m, SocketD.newEntity("no file! size: " + m.dataSize()));
                } else {
                    s.reply(m, SocketD.newEntity("file received: " + fileName + ", size: " + m.dataSize()));
                }
            }
        }).doOn("/download", (s, m) => {
            if (m.isRequest()) {
                let fileEntity = SocketD.newEntity("...");//todo://SocketD.newEntity(fs.readFileSync("/Users/noear/Movies/snack3-rce-poc.mov"));
                s.reply(m, fileEntity);
            }
        }).doOn("/push", (s, m) => {
            if (s.attrHas("push")) {
                return;
            }

            s.attrPut("push", "1");

            for (let i = 0; i++; i < 100) {
                if (s.attrHas("push") == false) {
                    break;
                }

                s.send("/push", SocketD.newEntity("push test"));
                //todo:sleep
            }
        }).doOn("/unpush", (s, m) => {
            s.attrMap().remove("push");
        })
        .doOnClose(s => {
            console.info("onClose: " + s.sessionId());
        }).doOnError((s, err) => {
            console.warn("onError: " + s.sessionId());
        });
}

main();

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=>{
      //异步获取答复(会多次回调)
})

视频演示效果:

代码仓库:

官网:

标签:node,Socket,newEntity,demo,SocketD,v2.3,js,let,reply
From: https://www.cnblogs.com/noear/p/17999743

相关文章

  • python网络编程笔记(一)Socket 编程入门
    一:Socket简介套接字起源于20世纪70年代加利福尼亚大学伯克利分校版本的Unix,即人们所说的BSDUnix。因此,有时人们也把套接字称为“伯克利套接字"或"BSD套接字”。一开始,套接字被设计用在同-台主机上多个应用程序之间的通讯BSDSocket接口是TCP/IP网络的API在Linux,Unix和W......
  • Prometheus+Grafana+Jmeter监控服务器资源及中间件(Prometheus & node_exporter &mysq
    一、Prometheus&node_exporter&Grafana的原理Prometheus:Prometheus是一个开源的系统监控和报警工具包,它负责定时从各种数据源(如NodeExporter)中获取指标数据,并将其存储在自己的时间序列数据库中。Prometheus支持灵活的查询和报警功能,用户可以方便地对这些指标数据进行查询......
  • React.ReactNode 和 React.ReactElement ,更推荐使用哪个?
    React.ReactNode和React.ReactElement,更推荐使用哪个?在React中,React.ReactNode和React.ReactElement是不同类型,它们适用于不同的场景:React.ReactNode:类型定义:typeReactNode=ReactChild|ReactFragment|ReactPortal|boolean|null|undefined;描述:这是一......
  • 在RunnerGo测试平台中做WebSocket、Dubbo、TCP/IP接口测试
    大家好,RunnerGo作为一款一站式测试平台不断为用户提供更好的使用体验,最近得知RunnerGo新增对,WebSocket、Dubbo、TCP/IP,三种协议API的测试支持,本篇文章跟大家分享一下使用方法。WebSocket协议WebSocket是一种在单个TCP连接上进行全双工通信的API技术。相比于传统的HTTP请求,We......
  • 在RunnerGo测试平台中做WebSocket、Dubbo、TCP/IP接口测试
    大家好,RunnerGo作为一款一站式测试平台不断为用户提供更好的使用体验,最近得知RunnerGo新增对,WebSocket、Dubbo、TCP/IP,三种协议API的测试支持,本篇文章跟大家分享一下使用方法。WebSocket协议WebSocket是一种在单个TCP连接上进行全双工通信的API技术。相比于传统的HTTP请......
  • dockerfile安装jenkins 并配置构建工具(node、npm、maven、git)
    dockerfile安装jenkins并配置构建工具(node、npm、maven、git):https://blog.csdn.net/weixin_39660224/article/details/88775707?ops_request_misc=&request_id=&biz_id=102&utm_term=dockerfile%20%E5%88%9B%E5%BB%BAjenkins&utm_medium=distribute.pc_search_result.......
  • 【NodeJS】- 使用NVM安装npm失败后,手动安装npm
    安装NVM之后,我们通常会配置镜像,在setting文件中,添加镜像路径node_mirror:https://npm.taobao.org/mirrors/nodenpm_mirror:https://npm.taobao.org/mirrors/npm但是这两天镜像突然炸了,于是我删掉了镜像地址,使用官方直接下载。但是npm下载非常困难,而且高版本的npm还存在wo......
  • nodejs 组件引入
    constfs=require("fs");constnodePath=require("path");//import*asfsfrom"fs";constfolder="./";constcondition=["node_modules","compile"];letarr:string[]=[];main(folder,......
  • nvm管理node
    -//nvm用来管理node版本//下载地址https://github.com/coreybutler/nvm-windows/releases//下载nvm-setup.exe//常用命令//nvmlistavailable显示所有可以下载的nodejs版本//nvmlist显示已安装的版本//nvminstall18.12.1安装18.12.1的nodejs//nvmins......
  • node后端中sql使用的表达式和函数
    参考:https://xiaoman.blog.csdn.net/article/details/135903790一.表达式MySQL表达式是一种在MySQL数据库中使用的计算式或逻辑式。它们可用于查询、更新和过滤数据,以及进行条件判断和计算。算术表达式:可以执行基本的数学运算,例如加法、减法、乘法和除法。例如:SELECTcol1+co......