@@ -13,34 +13,47 @@ brave.on('loadProtoByStdio', function ()
1313 end
1414end )
1515
16- brave .on (' loadProtoBySocket' , function (fdHandle )
16+ brave .on (' loadProtoBySocket' , function (param )
1717 local jsonrpc = require ' jsonrpc'
1818 local socket = require ' bee.socket'
19- local thread = require ' bee.thread '
20- local fd = socket .fd (fdHandle )
19+ local rfd = socket . fd ( param . rfd )
20+ local wfd = socket .fd (param . wfd )
2121 local buf = ' '
22- while true do
23- local proto , err = jsonrpc . decode ( function ( len )
24- while true do
25- if # buf >= len then
26- local res = buf : sub ( 1 , len )
27- buf = buf : sub ( len + 1 )
28- return res
29- end
30- local data = fd : recv ( )
31- if data then
32- buf = buf .. data
33- else
34- thread . sleep ( 0.01 )
22+
23+ --- @async
24+ local parser = coroutine.create ( function ()
25+ while true do
26+ --- @async
27+ local proto , err = jsonrpc . decode ( function ( len )
28+ while true do
29+ if # buf >= len then
30+ local res = buf : sub ( 1 , len )
31+ buf = buf : sub ( len + 1 )
32+ return res
33+ end
34+ coroutine.yield ( )
3535 end
36+ end )
37+ -- log.debug('loaded proto', proto.method)
38+ if not proto then
39+ brave .push (' protoerror' , err )
40+ return
3641 end
37- end )
38- -- log.debug('loaded proto', proto.method)
39- if not proto then
40- brave .push (' protoerror' , err )
41- return
42+ brave .push (' proto' , proto )
4243 end
43- brave .push (' proto' , proto )
44+ end )
45+
46+ while true do
47+ socket .select ({rfd , wfd }, nil , 10 )
48+ local needSend = wfd :recv ()
49+ if needSend then
50+ rfd :send (needSend )
51+ end
52+ local recved = rfd :recv ()
53+ if recved then
54+ buf = buf .. recved
55+ end
56+ coroutine.resume (parser )
4457 end
4558end )
4659
0 commit comments