-
Notifications
You must be signed in to change notification settings - Fork 8
/
room_chat.html
233 lines (207 loc) · 7.75 KB
/
room_chat.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>채팅 테스트</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
<style>
.chat-message > div {
background-color: #3b3b3b;
color: #e1e1e1;
border-radius: 0.8em;
padding: 0.4em;
margin: 0.4em 0;
display: inline-block;
white-space: pre-wrap;
max-width: 80%;
word-wrap: break-word;
}
.chat-message.me {
text-align: right;
}
.chat-message.me > div {
background-color: #1f8cff;
color: #fff;
text-align: left;
}
</style>
</head>
<body>
<!-- TODO: 웹소켓으로 실시간 채팅 기능 구현하기 -->
<div class="container my-5">
<div class="row">
<div class="col-sm-12">
<div class="card" style="height: 600px;">
<div class="card-header">
</div>
<div class="card-body overflow-hidden">
<div id="chat_messages" class="w-100 h-100 border-0 overflow-scroll"></div>
</div>
<div class="card-footer">
<form id="message_form">
<input type="text" name="message" class="form-control" autofocus="autofocus" autocomplete="off"/>
</form>
</div>
</div>
</div>
<hr class="my-3"/>
</div>
<div class="container">
<div class="row">
<div class="col-sm-12">
<form id="ws_url_form" class="mt-3">
<div class="mb-3">
<label for="ws_url_input" class="form-label">WebSocket URL:</label>
<input type="text" id="ws_url_input" name="ws_url" class="form-control" placeholder="Enter WebSocket URL">
</div>
<button type="submit" class="btn btn-primary">Connect</button>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
<script>
const handlers = {
chat_messages_tag: null,
ws: null,
retry: 0,
init() {
this.chat_messages_tag = document.querySelector("#chat_messages");
document
.querySelector("#message_form").addEventListener("submit", this.onsubmit.bind(this));
document.querySelector("#ws_url_form").addEventListener("submit", this.onWSUrlSubmit.bind(this));
},
connect(ws_url) {
if(this.ws) this.ws.close();
this.ws = new WebSocket(ws_url || this.ws?.url);
this.ws.onopen = this.onopen.bind(this);
this.ws.onclose = this.onclose.bind(this);
this.ws.onerror = this.onerror.bind(this);
this.ws.onmessage = this.onmessage.bind(this);
},
reconnect() {
this.connect();
},
onopen() {
console.log("웹소켓 서버와 접속");
},
onclose(event) {
const close_code = event.code;
if(close_code === 4000){
this.modal("채팅창이 삭제되었습니다. 대기실로 이동합니다.", () => {
window.location.href = "{% url 'chat:index'%}";
});
}
if (!event.wasClean) {
console.error("웹소켓 서버가 죽었거나, 네트워크 장애입니다.");
if (this.retry < 3) {
this.retry += 1;
setTimeout(() => {
this.reconnect();
console.log(`[${this.retry}] 접속 재시도...`);
}, 1000 * this.retry)
} else {
console.log("웹소켓 서버에 접속할 수 없습니다. 대기실로 이동합니다.");
window.location.href = "{% url 'chat:index' %}";
}
}
},
onerror() {
console.log("웹소켓 에러가 발생했습니다. 대기실로 이동합니다.");
window.location.href = "{% url 'chat:index' %}";
},
onmessage(event) {
const message_json = event.data;
console.log("메세지 수신: ", message_json);
const {type, message, sender, username} = JSON.parse(message_json);
switch (type) {
case "chat.message":
this.append_message(message, sender);
break;
case "chat.user.join":
this.append_message(`${username}님이 들어오셨습니다.`);
this.username_set.add(username);
this.update_user_list();
break;
case "chat.user.leave":
this.append_message(`${username}님이 나가셨습니다.`);
this.username_set.delete(username);
this.update_user_list();
break;
default:
console.error(`Invaild message type : ${type}`);
}
},
append_message(message, sender) {
const element = document.createElement("div");
element.className = "chat-message";
let footer ="";
if (sender === "{{ user.username }}") {
element.className += " me";
}
else if (sender) {
footer = ` from ${sender}`;
}
const wrapper = document.createElement("div");
wrapper.textContent = message;
element.appendChild(wrapper);
this.chat_messages_tag.appendChild(element);
this.chat_messages_tag.scrollTop = this.chat_messages_tag.scrollHeight;
},
onsubmit(event) {
event.preventDefault();
const form_data = new FormData(event.target);
const props = Object.fromEntries(form_data);
event.target.reset(); // reset form
const {message} = props;
console.log("웹소켓으로 전송할 메세지 :", message);
// this.append_message(message);
this.ws.send(JSON.stringify({type: "chat.message", message: message}))
},
update_user_list() {
const html = [...this.username_set]
.map(username => `<li>${username}</li>`)
.join('');
document.querySelector("#user_list").innerHTML = html;
document.querySelector("#user_count").textContent = `(${this.username_set.size}명)`;
},
modal(message, ok_handler){
const modal_ele = document.querySelector("#staticBackdrop");
const body_ele = modal_ele.querySelector(".modal-body");
const button_ele = modal_ele.querySelector(".modal-footer button");
body_ele.textContent = message;
button_ele.addEventListener("click", () => {
if(ok_handler) ok_handler();
modal.hide();
})
const modal = new bootstrap.Modal(modal_ele);
modal.show();
},
onWSUrlSubmit(event) {
event.preventDefault();
const wsUrlInput = document.querySelector("#ws_url_input");
const wsUrl = wsUrlInput.value;
fetch(wsUrl)
.then(response => response.json())
.then(data => {
console.log(data)
this.connect(data.chat_url);
})
// // Validate the WebSocket URL (add your own validation logic here)
// if (wsUrl) {
// console.log("Connecting to WebSocket:", wsUrl);
// this.connect(wsUrl); // Connect using the provided WebSocket URL
// } else {
// console.log("Please provide a valid WebSocket URL.");
// }
},
};
handlers.init();
// const protocol = location.protocol === "http:" ? "ws:" : "wss:";
// // const ws_url = protocol + "//" + 8000 + "/ws" + location.pathname;
// const ws_url = 'ws://localhost:8000/ws/chat/square/chat/'
// handlers.connect(ws_url);
</script>
</body>
</html>