Server Sent Events通过post方法传递参数

问题描述 投票:13回答:4

我正在使用Html5 Server Sent Events。服务器端是Java Servlet。我有一个想要传递给服务器的json数组数据。

var source = new EventSource("../GetPointVal?id=100&jsondata=" + JSON.stringify(data));

如果数组大小很小,服务器端可以获取查询字符串。但是如果阵列大小很大。 (可能超过数千个字符),服务器无法获取查询字符串。是否可以在new EventSource(...)中使用POST方法将json数组传递给服务器,以避免查询字符串长度限制?

json server-sent-events
4个回答
20
投票

不,SSE标准不允许POST。

(没有任何技术原因,据我所知 - 我认为只是设计师从未看过用例:它不仅仅是大数据,而且如果你想做一个自定义认证方案,那么安全原因不要将密码放在GET数据中。)

XMLHttpRequest(即AJAX)确实允许POST,因此一种选择是回到较旧的长轮询/彗星方法。 (我的书,Data Push Apps with HTML5 SSE详细介绍了如何做到这一点。)

另一种方法是预先将所有数据放入POST,并将其存储在HttpSession中,然后调用SSE进程,该进程可以利用该会话数据。 (SSE确实支持cookie,所以JSESSIONID cookie应该可以正常工作。)

附: standard没有明确表示不能使用POST。但是,与XMLHttpRequest不同,没有参数来指定要使用的http方法,也无法指定要发布的数据。


3
投票

虽然您无法使用EventSource API执行此操作,但没有技术原因可以解释为什么服务器无法实现POST请求。诀窍是让客户端发送请求。例如This answer discusses sse.js作为EventSource的替代品。


0
投票

或者,您可以从使用其他php自定义的文件中读取数据

http://..../command_receiver.php?command=blablabla

command_receiver.php

<?php
$cmd = $_GET['command'];
$fh = fopen("command.txt","w");
fwrite($fh, $cmd);
fclose($fh);
?>

demo2_sse.php

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

//$a = $_GET["what"];
$time = microtime(true); //date('r');

$fa = fopen("command.txt", "r");
$content = fread($fa,filesize("command.txt"));
fclose($fa);

echo "data: [{$content}][{$time}]\n\n";
flush();
?>

并且EventSource包含在任意命名的html中,如下所示

<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
var source = new EventSource("demo2_sse.php");
source.onmessage = function (event) {
        mycommand = event.data.substring(1, event.data.indexOf("]"));
       mytime = event.data.substring(event.data.lastIndexOf("[") + 1, event.data.lastIndexOf("]"));
}
</script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.