การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring
เรียนรู้การจัดการวงจรชีวิตการเชื่อมต่อ WebSocket ใน Spring ด้วยการจัดการเหตุการณ์เชื่อมต่อ ข้อความ ข้อผิดพลาด และยกเลิกการเชื่อมต่อผ่าน WebSocketHandler
การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Real-Time Systems with Spring และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The Connection Lifecycle
A WebSocket connection moves through clear stages: it opens, exchanges messages, may hit errors, and finally closes. Spring lets you hook into each stage to manage state and resources cleanly.
This lesson covers handling those lifecycle events.
The WebSocketHandler Interface
Spring's low-level API centers on the WebSocketHandler interface. Extending TextWebSocketHandler gives you override points for each lifecycle event without implementing every method.
Connection Established
afterConnectionEstablished fires when a client successfully connects. Use it to register the session and initialize per-connection state.
@Override
public void afterConnectionEstablished(WebSocketSession session) {
sessions.put(session.getId(), session);
System.out.println('Connected: ' + session.getId());
}Tracking Sessions
Keep active sessions in a thread-safe collection so you can broadcast and clean up. A ConcurrentHashMap keyed by session id is a common choice.
private final Map<String, WebSocketSession> sessions =
new ConcurrentHashMap<>();Handling Messages
handleTextMessage runs for each incoming message. Here you parse, validate, and act on the payload, then optionally reply or broadcast.
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
session.sendMessage(new TextMessage('echo: ' + payload));
}Handling Transport Errors
handleTransportError is called when a low-level error occurs on the connection. Log the problem and close the session gracefully if it cannot recover.
@Override
public void handleTransportError(WebSocketSession session, Throwable ex) throws Exception {
System.out.println('Transport error: ' + ex.getMessage());
if (session.isOpen()) {
session.close(CloseStatus.SERVER_ERROR);
}
}Connection Closed
afterConnectionClosed fires when the connection ends, whether the client left or the server closed it. Always clean up here to avoid leaks.
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
sessions.remove(session.getId());
System.out.println('Closed: ' + status.getCode());
}Close Status Codes
Close events carry a status code explaining why:
- 1000 Normal closure
- 1001 Going away (page unload)
- 1006 Abnormal closure (no close frame)
- 1011 Server error
Logging these helps diagnose connection problems.
Registering the Handler
Wire the handler to a path in a configuration class implementing WebSocketConfigurer.
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), '/ws')
.setAllowedOrigins('https://app.example.com');
}Cleaning Up Resources
Per-connection resources (timers, subscriptions, buffers) must be released on close and on error. Failing to do so causes memory leaks that grow with every dropped connection.
Heartbeats and Idle Timeouts
Dead connections may never fire a clean close. Use ping/pong heartbeats or idle timeouts to detect and reap stale sessions so your session map stays accurate.
Quick Check
Test your understanding of the WebSocket lifecycle.
Recap
You learned to handle the WebSocket lifecycle in Spring with TextWebSocketHandler: track sessions on connect, process messages, handle transport errors, and clean up on close. Close status codes, heartbeats, and idle timeouts keep your connection state healthy and leak-free.
เรียนรู้ WebSockets & Real-Time Systems with Spring ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring”
เรียนรู้การจัดการวงจรชีวิตการเชื่อมต่อ WebSocket ใน Spring ด้วยการจัดการเหตุการณ์เชื่อมต่อ ข้อความ ข้อผิดพลาด และยกเลิกการเชื่อมต่อผ่าน WebSocketHandler คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม
ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- Spring Boot สำหรับ WebSockets
- การตั้งค่าเอ็นด์พอยต์ WebSocket
- การส่งข้อความระหว่างไคลเอ็นต์กับเซิร์ฟเวอร์เบื้องต้น
- การจัดการเหตุการณ์วงจรชีวิตของ WebSocket ใน Spring