-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
33 lines (28 loc) · 1.52 KB
/
script.js
File metadata and controls
33 lines (28 loc) · 1.52 KB
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
// เชื่อมต่อกับ WebSocket Server
const socket = new WebSocket('ws://localhost:8080');
// ส่วนของ UI
const sendBtn = document.getElementById('sendBtn');
const messageInput = document.getElementById('message');
const responseDiv = document.getElementById('response');
// เมื่อเชื่อมต่อกับเซิร์ฟเวอร์สำเร็จ
socket.onopen = () => {
console.log('เชื่อมต่อกับเซิร์ฟเวอร์สำเร็จ');
};
// รับข้อความตอบกลับจากเซิร์ฟเวอร์
socket.onmessage = (event) => {
responseDiv.innerHTML = `เซิร์ฟเวอร์ตอบกลับ: ${event.data}`;
};
// ส่งข้อความไปยังเซิร์ฟเวอร์เมื่อกดปุ่ม
sendBtn.addEventListener('click', () => {
const message = messageInput.value;
if (message.trim()) {
socket.send(message); // ส่งข้อความไปยังเซิร์ฟเวอร์
messageInput.value = ''; // ล้างช่องข้อความหลังจากส่ง
} else {
alert('กรุณากรอกข้อความ');
}
});
// แจ้งเตือนเมื่อการเชื่อมต่อถูกตัด
socket.onclose = () => {
console.log('ตัดการเชื่อมต่อจากเซิร์ฟเวอร์');
};