FAQ > 金融建模 > 第三方交互 > TS-OPI

Q:TSL&OPI-SSE模式请求结果的解析    

  • A:SSE模式请求下,接收到的结果中除了请求结果数据外,还包括比如事件类型等数据。其中,请求结果存放在data字段中。
    在TSL中,我们推荐,可以先封装一个解析模型,以后只要是SSE模式的请求结果,都可通过该方式进行第一步解析,将收集到的数据拆分成结构化的数据,方便引用。
    其它语言中,用户也可以实现类似的功能封装。

    SSE模式请求结果的解析过程实现
    第一步:解析新增模型TD_ParsSSEMsg(Value)
    参数:Value即为SSE模式下接收到的字符串内容
    返回:以字段为下标,对应内容为单元值的数组。
    Function TD_ParsSSEMsg(Value);
    Begin
       lst:=new tstringList();
       lst.text:=Value;
       lst.NameValueSeparator:=":";
       ret:= array();
       for i:=0 to lst.count-1 do
       begin
        tmp:=lst.strings(i);
        a:= lst.names(i);
        if a<>"" then //去掉空行
         ret[LowerCase(a)]:=TrimLeft(lst.values(a));
       end;
       return ret;
    End;

    TD_ParsSSEMsg(Value)模式之后,我们再对订阅到的串进行处理。
    第二步:对SSE模式请求结果进行解析
    //如res为请求到的结果串
    ds:=TD_ParsSSEMsg(res);
    if istable(ds) then
      subData:=Importjsonstring(ds["data"]);

    subData生成结构如下,其中subData["CmdData"]即为订阅到的行情数据表格:
    array("CmdType":"Quotations","CmdData":
    (
    ("ID":"SH000001","date_s":"2026-06-05 10:39:59","price":4061.255),
    ("ID":"SH600519","date_s":"2026-06-05 10:39:59","price":1270.03)))

    应用示例:对通过SSE模式进行行情订阅结果的解析
    //********************Subscription:/Service/Subscription/********************************
    url:='https://opi.tinysoft.com.cn/Service/Subscription/'; //
    tbody:=array("Type":1,"IDs":("SH600519","SH000001"),"SUBs":("date_s","price","amount"));
    body:=ExportJsonString(tbody);
    //SSE模式---不支持TS-BOUNDARY: end
    headArr:=array("Connection: keep-alive","Content-Type: application/json","JSON-Encode: gbk","Accept: text/event-stream","TS-EVENTNAME: auto");
    header:=array2str(headArr,"\r\n");
    sid:=CreateHttpSession();
    sethttpMode(sid,1);//设置chunked模式(分段模式),分段输出模式
    while timeof(now())<strtotime("15:30:00") do
    begin
      r:=InternetRequest(sid,url,"",header,body,tuser,tpassw,0,res,resp,30000);//超时请求连接会中断
      echo "->r:",r,"->resp:",resp,"->res:",res,"\r\n";
      ds:=TD_ParsSSEMsg(res);
      if istable(ds) then
      begin
        subData:=Importjsonstring(ds["data"]);
        echo "subData->",tostn(subData),"\r\n";
      end
    end;
    return ;

    打印如下,即,将json串转换成了结构化的数组类型:
    ->r:1->resp:1000->res:event: subscription
    data: {"CmdType":"Quotations","CmdData":[{"ID":"SH000001","date_s":"2026-06-05 10:54:56","price":4069.6792,"amount":722469282071.5999},{"ID":"SH600519","date_s":"2026-06-05 10:54:55","price":1272.1,"amount":1944504908.0}]}


    subData->
    array("CmdType":"Quotations","CmdData":
    (
    ("ID":"SH000001","date_s":"2026-06-05 10:54:56","price":4069.6792,"amount":722469282071.6),
    ("ID":"SH600519","date_s":"2026-06-05 10:54:55","price":1272.1,"amount":1944504908.0)))