< >
    首页

    仓颉语言实现的Json流式解析库及以此为基础的RPC库

    源代码:

    一、jsonstream流式解析库

    提供两个类 JsonStreamClientJsonStreamServer 在网络上发送(Client)和接收(Server) encoding.json.JsonValue 对象。

    初始化:

    对象方法:

    用法:

    首先在 cjpm.toml[dependencies] 增加一行jsonstream = {git = "https://gitee.com/rocket049/jsonstream-cj.git", branch = "master"}, 接着运行 cjpm update

    示例代码:

    
    import std.socket.*
    import encoding.json.*
    import std.sync.*
    import std.time.*
    import std.collection.*
    import jsonstream.*
    
    main(): Int64 {
        let svr = TcpServerSocket(bindAt:9000)
        svr.bind()
        let futures = ArrayList<Future<Unit>>()
    
        spawn{
            sleep( Duration.second )
            tryClient("t1")
        }
        spawn{
            sleep( Duration.second )
            tryClient("t2")
        }
        spawn{
            sleep( Duration.second )
            tryClient("t3")
        }
        
        for(_ in 0..3) {
            let sock:TcpSocket = svr.accept()
            let t = spawn {
                let server = JsonStreamServer(sock)
                server.serve()
                while(true){
                    let v = server.getJsonValue()
                    if(v.isNone()){
                        break
                    }
                    let ret = v??JsonValue.fromStr("[]")
                    println(ret.toJsonString())
                }
            }
            futures.append(t)
        }
        for(t in futures){
            t.get() //等待线程结束
        }
        return 0
    }
    
    func tryClient(f:String){
        let conn = TcpSocket("127.0.0.1", 9000)
        conn.connect()
        let jsons = ArrayList<String>()
        for(i in 0..30) {
            jsons.append("{\"name\":\"${f}\",\"v\":${i}}")
        }
        let client = JsonStreamClient<TcpSocket>(conn)
        for(i in 0..jsons.size){
            let v = JsonValue.fromStr(jsons[i])
            client.send(v)
        }
        conn.flush()
        conn.close()
    }
    

    二、RPC库

    类和类型定义:

    初始化:

    对象方法:

    示例代码:

    吐槽:仓颉语言的对象序列化和反序列化代码都得手搓,远不如go语言的jsongob两个标准库强大!

    备案号:苏ICP备19034936号/ 苏ICP备19034936号-1/ 苏ICP备19034936号-2A    站长邮箱:fuhuizn@163.com   版权所有

    苏公网安备 32050702010684号

    Powered by MarkdownWeb