回答編集履歴
2
調整
answer
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
ポイントはSSEがメッセージを発生させるためのトリガーをどうするか次第ですね
|
|
4
4
|
|
|
5
5
|
# SSE簡易チャット
|
|
6
|
+
※微調整しました
|
|
6
7
|
|
|
7
8
|
- chat.html
|
|
8
9
|
```html
|
|
@@ -17,6 +18,9 @@
|
|
|
17
18
|
box.appendChild(Object.assign(document.createElement('div'),{textContent:json.message}));
|
|
18
19
|
box.scrollTop = box.scrollHeight;
|
|
19
20
|
}
|
|
21
|
+
evtSource.addEventListener('keep-alive',e=>{
|
|
22
|
+
console.log(JSON.parse(e.data).message);
|
|
23
|
+
});
|
|
20
24
|
send.addEventListener('click',e=>{
|
|
21
25
|
const usp=new URLSearchParams();
|
|
22
26
|
if(message.value){
|
|
@@ -57,23 +61,29 @@
|
|
|
57
61
|
header("Content-Type: text/event-stream");
|
|
58
62
|
date_default_timezone_set("Asia/Tokyo");
|
|
59
63
|
$mt=microtime(true);
|
|
64
|
+
$prev_mt=$mt;
|
|
65
|
+
$file = new SplFileObject($filename, "r");
|
|
60
66
|
while (true) {
|
|
61
|
-
$file = new SplFileObject($filename, "r");
|
|
62
67
|
foreach ($file as $line) {
|
|
63
68
|
if(preg_match("/^\[([\d\.]+)\](.+?)$/",$line,$match)){
|
|
64
69
|
if($match[1]-$mt > 0){
|
|
65
70
|
print "event: message".PHP_EOL;
|
|
66
71
|
print "data:{\"message\":".json_encode($match[2])."}".PHP_EOL.PHP_EOL;
|
|
67
|
-
print str_repeat(' ',4096).PHP_EOL
|
|
72
|
+
print str_repeat(' ',4096).PHP_EOL;
|
|
68
73
|
}
|
|
69
74
|
}
|
|
70
|
-
ob_end_flush();
|
|
71
|
-
flush();
|
|
72
75
|
}
|
|
73
|
-
|
|
76
|
+
flush();
|
|
77
|
+
if($mt-$prev_mt>30){
|
|
78
|
+
print "event: keep-alive".PHP_EOL;
|
|
79
|
+
print "data:{\"message\":\"".date("Y-m-d H:i:s")."\"}".PHP_EOL.PHP_EOL;
|
|
80
|
+
print str_repeat(' ',4096).PHP_EOL.PHP_EOL;
|
|
81
|
+
$prev_mt=$mt;
|
|
82
|
+
}
|
|
74
83
|
if ( connection_aborted() ) break;
|
|
75
84
|
$mt=microtime(true);
|
|
85
|
+
usleep(100000);
|
|
76
86
|
}
|
|
77
87
|
}
|
|
78
|
-
``
|
|
88
|
+
``
|
|
79
89
|
|
1
調整
answer
CHANGED
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
<?PHP
|
|
47
47
|
$q=filter_input(INPUT_GET,"q");
|
|
48
48
|
$m=filter_input(INPUT_GET,"m");
|
|
49
|
+
$filename="chat.txt";
|
|
49
50
|
if($q=="send"){
|
|
50
|
-
$filename="chat.txt";
|
|
51
51
|
$file = new SplFileObject($filename, "a+");
|
|
52
52
|
$file->fwrite('['.microtime(true).']'.$m.PHP_EOL);
|
|
53
53
|
exit;
|
|
@@ -58,7 +58,6 @@
|
|
|
58
58
|
date_default_timezone_set("Asia/Tokyo");
|
|
59
59
|
$mt=microtime(true);
|
|
60
60
|
while (true) {
|
|
61
|
-
$filename="chat.txt";
|
|
62
61
|
$file = new SplFileObject($filename, "r");
|
|
63
62
|
foreach ($file as $line) {
|
|
64
63
|
if(preg_match("/^\[([\d\.]+)\](.+?)$/",$line,$match)){
|