回答編集履歴

1

チャット

2025/05/23 07:42

投稿

yambejp
yambejp

スコア117726

test CHANGED
@@ -25,3 +25,82 @@
25
25
  };
26
26
  </script>
27
27
  ```
28
+
29
+ # chatの実装
30
+ だいぶ端折ってますが最低限動く範囲で実装しておきます
31
+ chat.html
32
+ ```html
33
+ <script>
34
+ window.addEventListener('DOMContentLoaded', ()=>{
35
+ const box=document.querySelector('#box');
36
+ const message=document.querySelector('#message');
37
+ const send=document.querySelector('#send');
38
+ send.addEventListener('click',e=>{
39
+ const usp=new URLSearchParams();
40
+ if(message.value){
41
+ usp.append('m',message.value);
42
+ fetch('sendapi.php?'+usp);
43
+ message.value='';
44
+ }
45
+ });
46
+ message.addEventListener('keydown',e=>{
47
+ if(e.key=="Enter"){
48
+ send.click();
49
+ }
50
+ });
51
+ });
52
+ const evtSource = new EventSource("sseapi.php",);
53
+ evtSource.onmessage = function (event) {
54
+ const json=JSON.parse(event.data);
55
+ box.appendChild(Object.assign(document.createElement('div'),{textContent:json.message}));
56
+ box.scrollTop = box.scrollHeight;
57
+ };
58
+ </script>
59
+ <style>
60
+ #box{
61
+ width:500px;
62
+ height:300px;
63
+ background-Color:lightgray;
64
+ overflow-Y:scroll;
65
+ }
66
+ </style>
67
+ <div id="box">
68
+ </div>
69
+ <input id="message"><input type="button" id="send" value="send">
70
+ ```
71
+
72
+ sendapi.php
73
+ ```php
74
+ <?PHP
75
+ $m=filter_input(INPUT_GET,"m");
76
+ if($m){
77
+ $filename="chat.txt";
78
+ $file = new SplFileObject($filename, "a+");
79
+ $file->fwrite('['.microtime(true).']'.$m.PHP_EOL);
80
+ }
81
+ ```
82
+
83
+ sseapi.php
84
+ ```php
85
+ <?PHP
86
+ header("Cache-Control: no-store");
87
+ header("Content-Type: text/event-stream");
88
+ date_default_timezone_set("Asia/Tokyo");
89
+ $mt=microtime(true);
90
+ while (true) {
91
+ $filename="chat.txt";
92
+ $file = new SplFileObject($filename, "r");
93
+ foreach ($file as $line) {
94
+ if(preg_match("/^\[([\d\.]+)\](.+?)$/",$line,$match)){
95
+ if($match[1]-$mt > 0){
96
+ print "data:{\"message\":".json_encode($match[2])."}".PHP_EOL.PHP_EOL;
97
+ }
98
+ }
99
+ ob_end_flush();
100
+ flush();
101
+ }
102
+ if ( connection_aborted() ) break;
103
+ $mt=microtime(true);
104
+ sleep(1);
105
+ }
106
+ ```