//web.rest 服务端流式输出 import win.ui; /*DSG{{*/ var winform = win.form(text="web.rest - 服务端推送事件";right=753;bottom=434) winform.add( edit={cls="edit";left=20;top=12;right=734;bottom=404;edge=1;multiline=1;z=1} ) /*}}*/ /* 所有基于 web.rest.client 的客户端都支持支持 SSE( Server-Sent Events) 事件流( MIME 为 "text/event-stream" ), 基于 web.rest.jsonClient 或 web.rest.jsonLiteClient 的客户端则支持 ndjson/jsonl 流以及 JSON 对象数组格式的流。 流式输出接口: doc://library-guide/std/web/rest/client.html#stream */ import wsock.tcp.simpleHttpServer; var url = wsock.tcp.simpleHttpServer.startUrl(function(response,request,session){ while (true) { response.eventStream( event = "ping"; data = { time = time() }; ) sleep(1000); } /* //推送 ndjson 流 response.contentType = "application/x-ndjson"; while (true) { response.write( { time = time() },'\n' ) sleep(1000); } */ }) thread.invoke( function(url,winform){ import web.rest.jsonLiteClient; var http = web.rest.jsonLiteClient(); var eventSource = http.api(url) //参数 @2 或 参数@3 指定接收数据回调函数则自动支持 SSE,兼容 ndjson 流。 eventSource.get( , function(message){ //注意这里的 message 已经由 JSON 解析为单个对象 winform.edit.print("HTTP 服务端推送了事件",type(message)) winform.edit.print(message); //返回 false 则停止接收数据 //return false; } ) },url,winform ) winform.show(); win.loopMessage();