提供两个类 JsonStreamClient
和 JsonStreamServer
在网络上发送(Client
)和接收(Server
) encoding.json.JsonValue
对象。
初始化:
JsonStreamClient( let conn:T ) where T <:IOStream
JsonStreamServer( let conn:T ) where T <:IOStream
对象方法:
JsonStreamClient.send
函数 public func send(v:JsonValue) :Bool
发送对象。JsonStreamServer.serve
函数 public func serve()
调用后开始解析对象、缓存对象。JsonStreamServer.getJsonValue
函数 public func getJsonValue() :?JsonValue
从缓存队列取出一个对象,封装为Option<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()
}
public type RpcFunc = (JsonValue)->JsonValue
public class JsonRpcServer<T> where T <:IOStream
public class JsonRpcClient<T> where T <:IOStream
public JsonRpcServer(let conn:T)
public JsonRpcClient(let conn:T)
JsonRpcServer.put(k:String, f:RpcFunc)
JsonRpcServer.serve()
JsonRpcClient.call(f:String, args:JsonValue):?JsonValue
src/examples/rpcserver
src/examples/rpcclient
吐槽:仓颉语言的对象序列化和反序列化代码都得手搓,远不如go
语言的json
和gob
两个标准库强大!