- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 python 客户端从带有 node.js API 的服务器监听 SSE 事件
流程是我通过 call_notification.py
向 node.js API 发送了一个事件并运行 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
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
});
}
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))
#!/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 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
最佳答案
非常简短的回答你的问题:
服务器代码没有将 SSE 消息发送回客户端。
为什么?因为你需要遵循SSE格式。
根据 JASON BUTZ in Server-Sent Events With Node
You should send a
Connection
:keep-alive
header to ensure the client keeps the connection open as well. ACache-Control
header should be sent with the valueno-cache
to discourage the data being cached. Finally, theContent-Type
needs to be set totext/event-stream
.With all of that done a newline (\n) should be sent to the client and then the events can be sent. Events must be sent as strings, but what is in that string doesn’t matter. JSON strings are perfectly fine.
Event data must be sent in the format
"data: <DATA TO SEND HERE>\n"
.It’s important to note that at the end of each line should be a newline character. To signify the end of an event an extra newline character needs to be added as well.
Multiple data lines are perfectly fine.
When communicating using SSEs, a server can push data to your app whenever it wants, without the need to make an initial request. In other words, updates can be streamed from server to client as they happen.
SSEs open a single unidirectional channel between server and client.*
{name: "Alice"}
调用 API 端点,没有(可见)发生。 {name: "Bob"}
调用 API 端点, 客户端 Alice 收到一个 SSE,负载为 {name: "Bob", says: "Hi"}
. {name: "Carol"}
调用 API 端点,客户端 Alice 和 Bob 各自收到一个 SSE,其有效载荷为 {name: "Carol", says: "Hi"}
. {name: "Bob", says: "Bye"}
的 SSE| . Requests
中的一些代码。图书馆
docs/#passing-parameters-in-urls .
import json
import pprint
import requests
import sseclient # sseclient-py
# change the name for each client
input_json = {'name':'Alice'}
#input_json = {'name':'Bob'}
#input_json = {'name':'Carol'}
url = 'http://company.com/api/root_event_notification'
stream_response = requests.get(url, params=input_json, stream=True)
client = sseclient.SSEClient(stream_response)
# Loop forever (while connection "open")
for event in client.events():
print ("got a new event from server")
pprint.pprint(event.data)
urllib.urlencode()
在 URL 中将它们编码为查询参数。图书馆。
urllib3.PoolManager().request()
发出 http 请求所以你最终会得到一个流响应。
sseclient
库将事件数据作为 unicode 字符串返回。要将 JSON 对象转换回 python 对象(使用 python 字符串),请使用
byteify
,递归自定义函数(感谢
Mark Amery)。
import json
import pprint
import urllib
import urllib3
import sseclient # sseclient-py
# Function that returns byte strings instead of unicode strings
# Thanks to:
# [Mark Amery](https://stackoverflow.com/users/1709587/mark-amery)
def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
# change the name for each client
input_json = {'name':'Alice'}
#input_json = {'name':'Bob'}
#input_json = {'name':'Carol'}
base_url = 'http://localhost:3000/api/root_event_notification'
url = base_url + '?' + urllib.urlencode(input_json)
http = urllib3.PoolManager()
stream_response = http.request('GET', url, preload_content=False)
client = sseclient.SSEClient(stream_response)
# Loop forever (while connection "open")
for event in client.events():
print ("got a new event from server")
pprint.pprint(byteify(json.loads(event.data)))
var EventEmitter = require('events').EventEmitter;
var myEmitter = new EventEmitter;
function registerEventHandlers(req, res) {
// Save received parameters
const myParams = req.query;
// Define function that adds "Hi" and send a SSE formated message
const sayHi = function(params) {
params['says'] = "Hi";
let payloadString = JSON.stringify(params);
res.write(`data: ${payloadString}\n\n`);
}
// Define function that adds "Bye" and send a SSE formated message
const sayBye = function(params) {
params['says'] = "Bye";
let payloadString = JSON.stringify(params);
res.write(`data: ${payloadString}\n\n`);
}
// Register what to do when inside-server 'hello' event happens
myEmitter.on('hello', sayHi);
// Register what to do when inside-server 'goodbye' event happens
myEmitter.on('goodbye', sayBye);
// Register what to do when this channel closes
req.on('close', () => {
// Emit a server 'goodbye' event with "saved" params
myEmitter.emit('goodbye', myParams);
// Unregister this particular client listener functions
myEmitter.off('hello', sayHi);
myEmitter.off('goodbye', sayBye);
console.log("<- close ", req.query);
});
}
app.get("/api/root_event_notification", (req, res, next) => {
console.log("open -> ", req.query);
// Emit a inside-server 'hello' event with the received params
myEmitter.emit('hello', req.query);
// SSE Setup
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write('\n');
// Register what to do when possible inside-server events happen
registerEventHandlers(req, res);
// Code execution ends here but channel stays open
// Event handlers will use the open channel when inside-server events happen
})
Sending an event stream from the source is a matter of constructing a plaintext response, served with a text/event-stream Content-Type, that follows the SSE format. In its basic form, the response should contain a "data:" line, followed by your message, followed by two "\n" characters to end the stream
data
属性与从服务器发送的消息。
关于python - 为什么python客户端收不到SSE事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913442/
在浏览可用的内在函数时,我注意到没有地方可以看到水平的addsub / subadd指令可用。在过时的3DNow中可用!扩展名,但是出于明显的原因,它的使用是不实际的。是什么原因导致SSE3扩展中无法
我需要在 SSE2 汇编程序中编写一些东西。 我所看到的都是内在因素。 我一直在寻找从内在函数到汇编器的转换表,但一直没有找到。 因为我不想玩猜谜游戏,有人可以给我一个链接,将这些可怕的内在函数转换为
我正在研究 SSE 并且是这里的新手。我正在尝试使用 shuffle 指令来随机播放一个 16 位向量,如下所示: 输入: 1 2 3 4 5 6 7 8 输出: 1 5 2 6 3 7 4 8 如何
我有一个用例,其中 x86 CPU 必须将 64 字节的数据写入内存已 mmapp 到用户空间的 PCIe 从属设备。截至目前,我使用 memcpy 来执行此操作,但事实证明它非常慢。我们可以使用像
我最近偶然发现了隐式 SSE/AVX 加载/存储。我认为这些是 GCC 的一些特殊扩展,但后来意识到它们也适用于 MSVC。 __m128 a = *(__m128*)data // same
仅将较高或较低 64 位从整数 SSE 寄存器移动到另一个的最快方法是什么?使用 SSE 4.1,可以使用单个 pblendw 来完成。指令(_mm_blend_epi16)。但是旧的 SSE 版本呢
SSE/AVX 寄存器可以被视为整数或浮点 BigNum。也就是说,人们可能会忽略车道的存在。是否存在一种简单的方法来利用这个观点并将这些寄存器单独或组合用作 BigNum?我问这个问题是因为从我对
我正在尝试比较 SSE float[4] 添加与标准 float[4] 添加。作为演示,我在使用和不使用 SSE 的情况下计算求和分量的总和: #include #include struct P
我处于以下情况: 我正在为不允许 SSE 指令的内核编写代码 我需要做浮点运算 我正在为 x86_64 平台编译 这是一个说明问题的代码示例: int main(int argc, char** ar
我处于以下情况: 我正在为不允许 SSE 指令的内核编写代码 我需要做浮点运算 我正在为 x86_64 平台编译 这是一个说明问题的代码示例: int main(int argc, char** ar
我正在尝试将用 SSE3 内在函数编写的代码转换为 NEON SIMD,但由于 shuffle 函数而卡住了。我查看了 GCC Intrinsic , ARM manuals和其他论坛,但一直无法找到
我正在尝试对一些代码进行 super 优化,我想加快速度的地方如下。 我想取一个 _m128 的点积运算 (_mm_dp_ps) 的答案,并将答案直接保存到寄存器中。但是,使用 _mm_store,这
我正在寻找 SSE 和 AVX 的 SIMD 数学库(最好是开源的)。我的意思是,例如,如果我有一个带有 8 个浮点值的 AVX 寄存器 v,我希望 sin(v) 一次返回所有八个值的 sin。 AM
假设我在 128 位变量/寄存器中有 16 个 ascii 字符(因此有 16 个 8 位数字)。我想创建一个位掩码,其中那些位将是高位,其位位置(索引)由这 16 个字符表示。 例如,如果由这 16
目前我正在使用 Visual C++ 内联汇编使用 SSE 嵌入一些核心功能;但是我意识到 x64 模式不支持内联汇编。 在 x64 架构中构建软件时如何使用 SSE? 最佳答案 在 C/C++ 中使
我正在寻找计算以下函数的有效方法: 输入:__m128i数据,uint8_t in; 输出: bool 值,指示 data 中的任何字节是否在 in 中。 我实际上是在使用它们为容量为 8 的字节实现
我正在寻找计算以下函数的有效方法: 输入:__m128i数据,uint8_t in; 输出: bool 值,指示 data 中的任何字节是否在 in 中。 我实际上是在使用它们为容量为 8 的字节实现
我正在尝试将最新消息拉入顶部页面。目前,每次收到新消息时,最新消息都会显示在下方。 if(typeof(EventSource)!=="undefined") { var source=new Ev
基本上我想做的是获取一个 __m128i 寄存器并将每个负字节的值设置为 -128 (0x80) 并且不更改任何正值。 确切的是: signed char __m128_as_char_arr[16]
有 2 个指针指向要加载到 xmm 寄存器中的 2 个未对齐的 8 字节 block 。如果可能,使用内在函数。如果可能的话,不使用辅助寄存器。没有pinsrd。 (SSSE核心2) 最佳答案 来自
我是一名优秀的程序员,十分优秀!