use*_*827 5 python node.js server-sent-events
我有一个 python 客户端从带有 node.js API 的服务器监听 SSE 事件
流程是我通过向 node.js API 发送一个事件call_notification.py并seevents.py使用循环运行run.sh(见下文)
但是我没有看到 python 客户端正在接收这个 SSE 事件?关于为什么会这样的任何指导?
call_notification.py
import requests
input_json = {'BATS':'678910','root_version':'12A12'}
url = 'http://company.com/api/root_event_notification?params=%s'%input_json
response = requests.get(url)
print response.text
Run Code Online (Sandbox Code Playgroud)
节点.js API
app.get("/api/root_event_notification", (req, res, next) => {
console.log(req.query.params)
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
console.log('new_root_announced!');
res.status(200).json({
message: "New root build released!",
posts: req.query.params
});
}
Run Code Online (Sandbox Code Playgroud)
seeevents.py(python 客户端监听 SSE 事件)
import json
import pprint
import sseclient
def with_urllib3(url):
"""Get a streaming response for the given event feed using urllib3."""
import urllib3
http = urllib3.PoolManager()
return http.request('GET', url, preload_content=False)
def with_requests(url):
"""Get a streaming response for the given event feed using requests."""
import requests
return requests.get(url, stream=True)
url = 'http://company.com/api/root_event_notification'
response = with_urllib3(url) # or with_requests(url)
client = sseclient.SSEClient(response)
#print client.events()
for event in client.events():
print "inside"
pprint.pprint(json.loads(event.data))
Run Code Online (Sandbox Code Playgroud)
运行文件
#!/bin/sh
while [ /usr/bin/true ]
do
echo "Running sseevents.py"
python sseevents.py 2>&1 | tee -a sseevents.log.txt
echo "sleeping for 30 sec"
sleep 30
done
Run Code Online (Sandbox Code Playgroud)
输出:-
Run call_notification.py on Terminal
node.js API OUTPUT
new_root_announced!
{'root_version': 'ABCD', 'BATS': '143'}
./run.sh --> DON'T SEE ABOVE EVENT below
Running sseevents.py
sleeping for 30 sec
Running sseevents.py
sleeping for 30 sec
Running sseevents.py
sleeping for 30 sec
Run Code Online (Sandbox Code Playgroud)
服务器代码不会将 SSE 消息发送回客户端。
\n\n为什么?因为你需要遵循SSE格式。
\n\n根据JASON BUTZ 在 Server-Sent Events With Node 中的说法
\n\n\n\n\n您应该发送
\n\nConnection:keep-alive标头以确保客户端也保持连接打开。Cache-Control应发送带有值的标头,以no-cache阻止缓存数据。最后,Content-Type需要设置为text/event-stream。完成所有这些后,应将换行符 (\\n) 发送到客户端,然后可以发送事件。事件必须作为字符串发送,但该字符串中的内容并不重要。JSON 字符串完全没问题。
\n\n事件数据必须以 格式发送
\n\n"data: <DATA TO SEND HERE>\\n"。\xe2\x80\x99s 需要注意的是,每行末尾应该有一个换行符。为了表示事件的结束,还需要添加额外的换行符。
\n\n多条数据线完全没问题。
\n
根据Eric Bidelman 在 html5rocks.com 中的说法:
\n\n\n\n\n使用 SSE 进行通信时,服务器可以随时将数据推送到您的应用程序,而无需发出初始请求。换句话说,更新可以在发生时从服务器传输到客户端。
\n
但是,为了实现这一点,客户端必须通过请求来“开始”并准备接收消息流(当它们发生时)。
\n\n\n\n\nSSE 在服务器和客户端之间打开一个单向通道。*
\n
* 重点是我的
\n\n这意味着服务器有一个到客户端的“直接”通道。它不打算由非“客户端”代码的其他进程/代码“启动”(打开)。
\n\n假设从OP评论......
\n\n客户端 Alice 使用 params 调用 API 端点{name: "Alice"},没有(可见)发生任何事情。
...然后客户端 Bob 使用 params 调用 API 端点{name: "Bob"},客户端 Alice 接收带有 Payload 的 SSE {name: "Bob", says: "Hi"}。
...然后客户端 Carol 使用 params 调用 API 端点{name: "Carol"},客户端 Alice 和 Bob 各接收一个带有 Payload 的 SSE {name: "Carol", says: "Hi"}。
...等等。每次新客户端使用参数调用 API 端点时,具有“打开”通道的所有其他客户端都将收到带有新“Hi”有效负载的 SSE。
...然后客户端 Bob 与服务器“断开”连接,客户端 Alice、客户端 Carol 以及所有“打开”通道的客户端将收到带有有效负载的 SSE {name: "Bob", says: "Bye"}。
...等等。每次旧客户端与服务器“断开连接”时,通道“打开”的所有其他客户端都会收到带有新“Bye”有效负载的 SSE。
关于阻塞的注意事项 每个具有“开放”通道的客户端都将“陷入”无限等待事件发生的循环中。使用“线程”代码技术来避免阻塞是客户端设计的责任。
\n\n您的 Python 客户端应该“请求”启动单个单向通道并继续等待,直到通道关闭。不应以不同的频道结束并重新开始。它应该保持同一个通道打开。
\n\n从网络角度来看,它就像一个不会结束的“长”响应(直到 SSE 消息传递结束)。回应只是“不断出现”。
\n\n您的 Python 客户端代码就是这样做的。我注意到它是sseclient-py 库中使用的确切示例代码。
\n\n要包含要发送到服务器的参数,请使用库Requestsdocs /#passing-parameters-in-urls中的一些代码。
因此,混合这些示例后,我们最终得到以下代码作为您的 Python 3.4 客户端:
\n\nimport json\nimport pprint\nimport requests\nimport sseclient # sseclient-py\n\n# change the name for each client\ninput_json = {\'name\':\'Alice\'}\n#input_json = {\'name\':\'Bob\'}\n#input_json = {\'name\':\'Carol\'}\n\nurl = \'http://company.com/api/root_event_notification\'\nstream_response = requests.get(url, params=input_json, stream=True)\n\nclient = sseclient.SSEClient(stream_response)\n\n# Loop forever (while connection "open")\nfor event in client.events():\n print ("got a new event from server")\n pprint.pprint(event.data)\nRun Code Online (Sandbox Code Playgroud)\n\n要包含要发送到服务器的参数,请使用urllib.urlencode()库将它们编码为 URL 中的查询参数。
发出 http 请求,这样urllib3.PoolManager().request()您最终会得到一个流响应。
请注意,该sseclient库以 unicode 字符串形式返回事件数据。要将 JSON 对象转换回 python 对象(带有 python 字符串)byteify,请使用递归自定义函数(感谢Mark Amery)。
使用以下代码作为您的 Python 2.7 客户端:
\n\nimport json\nimport pprint\nimport urllib\nimport urllib3\nimport sseclient # sseclient-py\n\n# Function that returns byte strings instead of unicode strings\n# Thanks to:\n# [Mark Amery](/sf/users/119671121/)\ndef byteify(input):\n if isinstance(input, dict):\n return {byteify(key): byteify(value)\n for key, value in input.iteritems()}\n elif isinstance(input, list):\n return [byteify(element) for element in input]\n elif isinstance(input, unicode):\n return input.encode(\'utf-8\')\n else:\n return input\n\n# change the name for each client\ninput_json = {\'name\':\'Alice\'}\n#input_json = {\'name\':\'Bob\'}\n#input_json = {\'name\':\'Carol\'}\n\nbase_url = \'http://localhost:3000/api/root_event_notification\'\nurl = base_url + \'?\' + urllib.urlencode(input_json)\n\nhttp = urllib3.PoolManager()\nstream_response = http.request(\'GET\', url, preload_content=False)\n\nclient = sseclient.SSEClient(stream_response)\n\n# Loop forever (while connection "open")\nfor event in client.events():\n print ("got a new event from server")\n pprint.pprint(byteify(json.loads(event.data)))\nRun Code Online (Sandbox Code Playgroud)\n\n现在,服务器代码应该:
\n\n使用以下 Node.js API 代码:
\n\nvar EventEmitter = require(\'events\').EventEmitter;\nvar myEmitter = new EventEmitter;\n\n\nfunction registerEventHandlers(req, res) {\n // Save received parameters\n const myParams = req.query;\n\n // Define function that adds "Hi" and send a SSE formated message\n const sayHi = function(params) {\n params[\'says\'] = "Hi";\n let payloadString = JSON.stringify(params);\n res.write(`data: ${payloadString}\\n\\n`);\n }\n\n // Define function that adds "Bye" and send a SSE formated message\n const sayBye = function(params) {\n params[\'says\'] = "Bye";\n let payloadString = JSON.stringify(params);\n res.write(`data: ${payloadString}\\n\\n`);\n }\n\n // Register what to do when inside-server \'hello\' event happens\n myEmitter.on(\'hello\', sayHi);\n\n // Register what to do when inside-server \'goodbye\' event happens\n myEmitter.on(\'goodbye\', sayBye);\n\n // Register what to do when this channel closes\n req.on(\'close\', () => {\n // Emit a server \'goodbye\' event with "saved" params\n myEmitter.emit(\'goodbye\', myParams);\n\n // Unregister this particular client listener functions\n myEmitter.off(\'hello\', sayHi);\n myEmitter.off(\'goodbye\', sayBye);\n console.log("<- close ", req.query);\n });\n}\n\n\napp.get("/api/root_event_notification", (req, res, next) => {\n console.log("open -> ", req.query);\n\n // Emit a inside-server \'hello\' event with the received params\n myEmitter.emit(\'hello\', req.query);\n\n // SSE Setup\n res.writeHead(200, {\n \'Content-Type\': \'text/event-stream\',\n \'Cache-Control\': \'no-cache\',\n \'Connection\': \'keep-alive\',\n });\n res.write(\'\\n\');\n\n // Register what to do when possible inside-server events happen\n registerEventHandlers(req, res);\n\n // Code execution ends here but channel stays open\n // Event handlers will use the open channel when inside-server events happen\n})\nRun Code Online (Sandbox Code Playgroud)\n\n...继续在 html5rocks.com 中引用 Eric Bidelman 的话:
\n\n\n\n\n从源发送事件流需要构建一个纯文本响应,并提供遵循 SSE 格式的文本/事件流内容类型。在其基本形式中,响应应包含“data:”行,后跟您的消息,然后是两个“\\n”字符以结束流
\n
在客户端代码中,sseclient-py 库负责解释 SSE 格式,因此每次两个“ \\n”字符到达时,该库都会“迭代”一个新的“可迭代”对象(一个新事件),该对象具有以下data属性与从服务器发送的消息。
所以,代码可以正常工作:)
\n| 归档时间: |
|
| 查看次数: |
2781 次 |
| 最近记录: |