0

我正在尝试做一个与乐山演示服务器交互的http api。我试图在 LWM2M 中处理 OBSERVE,但我需要使用 http 处理通知。我发现乐山通知使用 SSE。所以我试图使用requests和sseclient在python中实现sse客户端。

这是我的代码:

    response= requests.post(url_request , "format=TLV" , stream= True)    
    client = sseclient.SSEClient(response)
    for event in client.events():
        print(json.loads(event.data))

我尝试运行我的脚本,但似乎流没有打开并且它立即关闭而不等待服务器的回答,即使默认情况下请求在 HTTP 下为 TCP 连接实现 keep_alive 并且流为 True。

有人知道为什么吗?

4

1 回答 1

0

阅读sseclient文档,使用 SSEClient 的正确方法似乎是:

from sseclient import SSEClient
messages = SSEClient('http://example.com/sse_stream/')
for msg in messages:
    do_something_useful(msg)

看了乐山Github上的答案,乐山服务器Demo的流URL好像是http://your.leshan.server.org/event?ep=your_device_endpoint_name

所以我尝试了:

from sseclient import SSEClient
messages = SSEClient('http://localhost:8080/event?ep=my_device')
for msg in messages:
    print (msg.event, msg.data)

它对我有用!当我观察 Leshan Client Demo 的温度实例时得到这种结果:

(u'NOTIFICATION', u'{"ep":"my_device","res":"/3303/0","val":{"id":0,"resources":[{"id":5601,"value":-18.9},{"id":5602,"value":31.2},{"id":5700,"value":-18.4},{"id":5701,"value":"cel"}]}}')
(u'COAPLOG', u'{"timestamp":1592296453808,"incoming":true,"type":"CON","code":"POST","mId":29886,"token":"889372029F81C124","options":"Uri-Path: \\"rd\\", \\"reWfKIgPYD\\"","ep":"my_device"}')
(u'COAPLOG', u'{"timestamp":1592296453809,"incoming":false,"type":"ACK","code":"2.04","mId":29886,"token":"889372029F81C124","ep":"my_device"}')
(u'UPDATED', u'{"registration":{"endpoint":"my_device","registrationId":"reWfKIgPYD","registrationDate":"2020-06-16T10:02:25+02:00","lastUpdate":"2020-06-16T10:34:13+02:00","address":"127.0.0.1:44400","lwM2mVersion":"1.0","lifetime":300,"bindingMode":"U","rootPath":"/","objectLinks":[{"url":"/","attributes":{"rt":"\\"oma.lwm2m\\""}},{"url":"/1/0","attributes":{}},{"url":"/3/0","attributes":{}},{"url":"/6/0","attributes":{}},{"url":"/3303/0","attributes":{}}],"secure":false,"additionalRegistrationAttributes":{}},"update":{"registrationId":"reWfKIgPYD","identity":{"peerAddress":{}},"additionalAttributes":{}}}')
(u'COAPLOG', u'{"timestamp":1592296455150,"incoming":true,"type":"NON","code":"2.05","mId":29887,"token":"3998C5DE2588F835","options":"Content-Format: \\"application/vnd.oma.lwm2m+tlv\\" - Observe: 2979","payload":"Hex:e3164563656ce8164408c03199999999999ae815e108c032e66666666666e815e208403f333333333333","ep":"my_device"}')

如果您只对通知感兴趣,只需添加一个if msg.event == 'NOTIFICATION':块。

于 2020-06-16T08:41:11.463 回答