[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"academy-blogs-th-1-1-all-golang-websocket-connection-management-all--*":3,"academy-blog-translations-sxza010k0ci2mzn":79},{"data":4,"page":67,"perPage":67,"totalItems":67,"totalPages":67},[5],{"alt":6,"collectionId":7,"collectionName":8,"content":9,"cover_image":10,"cover_image_path":11,"created":12,"created_by":13,"expand":14,"id":73,"keywords":74,"locale":49,"published_at":75,"scheduled_at":13,"school_blog":71,"short_description":76,"slug":77,"status":69,"title":6,"updated":78,"updated_by":13,"views":72},"EP.80 การสร้างระบบการจัดการการเชื่อมต่อ (Connection Management) ใน WebSocket Chat","sclblg987654321","school_blog_translations","\u003Cp>ระบบการจัดการการเชื่อมต่อ (Connection Management) คือหนึ่งในองค์ประกอบสำคัญของแอปพลิเคชันประเภท WebSocket Chat ที่มีผู้ใช้หลายคนใช้งานพร้อมกันแบบเรียลไทม์\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>หากไม่มีการจัดการที่ดี อาจเกิดปัญหา เช่น ส่งข้อความผิดคน, มี connection ค้างอยู่ในหน่วยความจำ (memory leak), หรือไม่สามารถรองรับผู้ใช้จำนวนมากได้\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔸 ทำไมต้องมีระบบจัดการการเชื่อมต่อ?\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>✅ ติดตามผู้ใช้งาน:\u003Cbr>รู้ว่าใครกำลังเชื่อมต่ออยู่ในระบบ และระบุได้ว่าเชื่อมต่อจากอุปกรณ์ไหน\u003C\u002Fp>\u003Cp>✅ ส่งข้อความได้ถูกต้อง:\u003Cbr>จำเป็นต้องรู้ว่า connection ของผู้ใช้อยู่ตรงไหน เพื่อส่งข้อความได้ตรงตัว\u003C\u002Fp>\u003Cp>✅ ตรวจจับการตัดการเชื่อมต่อ:\u003Cbr>เช่น กรณี timeout, user ปิดเบราว์เซอร์, หรือเน็ตหลุด\u003C\u002Fp>\u003Cp>✅ เพิ่มความเสถียรของระบบ:\u003Cbr>ลดโอกาสเกิด connection leak และช่วยให้ระบบรองรับผู้ใช้จำนวนมากได้อย่างยั่งยืน\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔸 โครงสร้างระบบ Connection Management ที่ดีควรมี\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cul>\u003Cli>Connection Hub (หรือ Connection Pool):\u003Cbr>เก็บรายการของผู้ใช้ที่เชื่อมต่อทั้งหมด\u003C\u002Fli>\u003Cli>User ↔ Connection Mapping:\u003Cbr>ผูก \u003Ccode inline=\"\">userID\u003C\u002Fcode> กับ connection เพื่อจัดการข้อความเฉพาะบุคคล\u003C\u002Fli>\u003Cli>Broadcast และ Private Messaging:\u003Cbr>รองรับทั้งการส่งข้อความแบบทุกคน (broadcast) และแบบเฉพาะคน (private)\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>✅ ตัวอย่างโค้ด Golang: ระบบจัดการการเชื่อมต่อแบบง่าย\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"sync\"\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\n    \"fmt\"\n)\n\n\u002F\u002F โครงสร้างของการเชื่อมต่อแต่ละคน\ntype Connection struct {\n    ws   *websocket.Conn\n    user string\n}\n\n\u002F\u002F Hub คือคลาสหลักที่เก็บการเชื่อมต่อทั้งหมด\ntype Hub struct {\n    connections map[string]*Connection \u002F\u002F key: userID\n    lock        sync.RWMutex\n}\n\n\u002F\u002F ฟังก์ชันสำหรับสร้าง Hub ใหม่\nfunc NewHub() *Hub {\n    return &amp;Hub{\n        connections: make(map[string]*Connection),\n    }\n}\n\n\u002F\u002F ✅ เพิ่มการเชื่อมต่อใหม่\nfunc (h *Hub) AddConnection(userID string, conn *websocket.Conn) {\n    h.lock.Lock()\n    defer h.lock.Unlock()\n\n    h.connections[userID] = &amp;Connection{\n        ws:   conn,\n        user: userID,\n    }\n\n    fmt.Printf(\"[+] %s connected\\n\", userID)\n}\n\n\u002F\u002F ✅ ลบการเชื่อมต่อเมื่อผู้ใช้ disconnect\nfunc (h *Hub) RemoveConnection(userID string) {\n    h.lock.Lock()\n    defer h.lock.Unlock()\n\n    if conn, ok := h.connections[userID]; ok {\n        conn.ws.Close() \u002F\u002F ปิด WebSocket\n        delete(h.connections, userID)\n        fmt.Printf(\"[-] %s disconnected\\n\", userID)\n    }\n}\n\n\u002F\u002F ✅ ส่งข้อความไปยังผู้ใช้เฉพาะคน\nfunc (h *Hub) SendToUser(userID string, message string) {\n    h.lock.RLock()\n    defer h.lock.RUnlock()\n\n    if conn, ok := h.connections[userID]; ok {\n        err := conn.ws.WriteMessage(websocket.TextMessage, []byte(message))\n        if err != nil {\n            fmt.Println(\"[x] Send to\", userID, \"failed:\", err)\n        }\n    }\n}\n\n\u002F\u002F ✅ ส่งข้อความไปยังผู้ใช้ทุกคน (broadcast)\nfunc (h *Hub) Broadcast(message string) {\n    h.lock.RLock()\n    defer h.lock.RUnlock()\n\n    for userID, conn := range h.connections {\n        err := conn.ws.WriteMessage(websocket.TextMessage, []byte(message))\n        if err != nil {\n            fmt.Println(\"[x] Broadcast to\", userID, \"failed:\", err)\n            conn.ws.Close()\n            delete(h.connections, userID)\n        }\n    }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>📝 สรุปสิ่งที่แต่ละฟังก์ชันทำ:\u003C\u002Fh3>\u003Cfigure class=\"table\">\u003Ctable>\u003Cthead>\u003Ctr>\u003Cth>ฟังก์ชัน\u003C\u002Fth>\u003Cth>หน้าที่\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\u003Ctbody>\u003Ctr>\u003Ctd>\u003Ccode inline=\"\">AddConnection\u003C\u002Fcode>\u003C\u002Ftd>\u003Ctd>เพิ่มการเชื่อมต่อใหม่เมื่อผู้ใช้เข้ามา\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>\u003Ccode inline=\"\">RemoveConnection\u003C\u002Fcode>\u003C\u002Ftd>\u003Ctd>ลบการเชื่อมต่อออกเมื่อผู้ใช้ disconnect\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>\u003Ccode inline=\"\">SendToUser\u003C\u002Fcode>\u003C\u002Ftd>\u003Ctd>ส่งข้อความแบบ private ให้ผู้ใช้คนใดคนหนึ่ง\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>\u003Ccode inline=\"\">Broadcast\u003C\u002Fcode>\u003C\u002Ftd>\u003Ctd>ส่งข้อความถึงผู้ใช้ทุกคนที่เชื่อมต่ออยู่\u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftbody>\u003C\u002Ftable>\u003C\u002Ffigure>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>✅ ตัวอย่างโค้ด Golang: ส่วน \u003Ccode inline=\"\">main()\u003C\u002Fcode> และ \u003Ccode inline=\"\">wsHandler()\u003C\u002Fcode> แบบเต็ม\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"fmt\"\n    \"net\u002Fhttp\"\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\n)\n\n\u002F\u002F ใช้ร่วมกับ Hub และ Connection ที่ประกาศไว้ก่อนหน้า\n\n\u002F\u002F ตัวแปรสำหรับ upgrade HTTP → WebSocket\nvar upgrader = websocket.Upgrader{\n    CheckOrigin: func(r *http.Request) bool {\n        return true \u002F\u002F อนุญาตให้ทุก origin เชื่อมต่อ (ควรปรับในโปรดักชัน)\n    },\n}\n\n\u002F\u002F ฟังก์ชันหลักที่จัดการ WebSocket แต่ละการเชื่อมต่อ\nfunc wsHandler(hub *Hub, w http.ResponseWriter, r *http.Request) {\n    \u002F\u002F Upgrade HTTP → WebSocket\n    ws, err := upgrader.Upgrade(w, r, nil)\n    if err != nil {\n        fmt.Println(\"[x] Upgrade error:\", err)\n        return\n    }\n\n    \u002F\u002F ดึง user ID จาก query parameter\n    userID := r.URL.Query().Get(\"user\")\n    if userID == \"\" {\n        fmt.Println(\"[x] Missing user ID in query parameter\")\n        ws.Close()\n        return\n    }\n\n    \u002F\u002F เพิ่ม connection เข้า Hub\n    hub.AddConnection(userID, ws)\n    defer hub.RemoveConnection(userID) \u002F\u002F ลบเมื่อ disconnect\n\n    for {\n        \u002F\u002F รอรับข้อความจาก client\n        _, msg, err := ws.ReadMessage()\n        if err != nil {\n            fmt.Println(\"[x] Read error from\", userID, \":\", err)\n            break\n        }\n\n        fmt.Printf(\"[&gt;] Received from %s: %s\\n\", userID, string(msg))\n\n        \u002F\u002F ส่งข้อความ broadcast ไปยังทุกคน\n        broadcastMsg := fmt.Sprintf(\"%s says: %s\", userID, string(msg))\n        hub.Broadcast(broadcastMsg)\n    }\n}\n\n\u002F\u002F ฟังก์ชัน main สำหรับเริ่มต้น WebSocket server\nfunc main() {\n    hub := NewHub() \u002F\u002F สร้าง Hub เก็บ connections\n\n    \u002F\u002F สร้าง endpoint \u002Fws\n    http.HandleFunc(\"\u002Fws\", func(w http.ResponseWriter, r *http.Request) {\n        wsHandler(hub, w, r)\n    })\n\n    fmt.Println(\"🚀 WebSocket server started at :8080\")\n    err := http.ListenAndServe(\":8080\", nil)\n    if err != nil {\n        fmt.Println(\"[x] Server failed:\", err)\n    }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>🔗 การเชื่อมต่อ:\u003C\u002Fh3>\u003Cp>หากผู้ใช้เชื่อมต่อผ่าน URL เช่น:\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">ws:\u002F\u002Flocalhost:8080\u002Fws?user=alice\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>ระบบจะ:\u003C\u002Fp>\u003Cul>\u003Cli>ดึง \u003Ccode inline=\"\">userID = \"alice\"\u003C\u002Fcode> จาก query string\u003C\u002Fli>\u003Cli>เพิ่ม connection ของ alice เข้า \u003Ccode inline=\"\">Hub\u003C\u002Fcode>\u003C\u002Fli>\u003Cli>รับข้อความจาก alice และ broadcast ไปยังทุกคนที่อยู่ในระบบ\u003C\u002Fli>\u003Cli>เมื่อ alice ปิด connection หรือหลุด ระบบจะลบ connection ทันที\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>💡 สิ่งที่โค้ดนี้ทำได้:\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>✅ เก็บ connection แต่ละคนในระบบ\u003Cbr>✅ รับและส่งข้อความแบบ broadcast และแบบเฉพาะเจาะจง\u003Cbr>✅ จัดการผู้ใช้ที่ disconnect อัตโนมัติ\u003Cbr>✅ รองรับผู้ใช้หลายคนพร้อมกันได้อย่างมีประสิทธิภาพ\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Chr>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔧 ท้าให้ลอง!\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>ลอง เพิ่มระบบ Timeout หรือ Inactivity Check เพื่อให้ระบบสามารถตัดการเชื่อมต่อของผู้ใช้ที่ไม่ได้ใช้งานนานเกินกำหนด เช่น:\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">time.AfterFunc(10*time.Minute, func() {\n    hub.RemoveConnection(userID)\n})\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>หรือใช้ \u003Ccode inline=\"\">ping\u002Fpong\u003C\u002Fcode> frame เพื่อตรวจสอบว่า connection ยังมีชีวิตอยู่หรือไม่\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔜 EP ถัดไป:\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>EP.81 – การใช้ WebSocket เชื่อมต่อกับระบบฐานข้อมูลแบบเรียลไทม์ (Real-Time DB Integration)\u003Cbr>เราจะพาคุณไปดูวิธีการเชื่อม WebSocket กับฐานข้อมูลเพื่อให้ทุกข้อความหรือ event ที่เกิดขึ้น ถูกบันทึกและซิงก์กับ Database ทันทีแบบ real-time!\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>\u003Cstrong>อ่านบทความ Series อื่นๆ\u003C\u002Fstrong>\u003C\u002Fp>\u003Cul>\u003Cli>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fblogs\u002Fcategories\u002FGolang\">\u003Cstrong>Golang The Series\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fli>\u003Cli>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fblogs\u002Fcategories\u002FJS2GO\">\u003Cstrong>JS2GO\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fli>\u003Cli>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fblogs\u002Fcategories\u002FTailwind%20CSS\">\u003Cstrong>10 Ep ที่จะให้คุณเป็นมือโปร Tailwind CSS ในชั่วข้ามคืน\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fli>\u003C\u002Ful>\u003Cp>\u003Cstrong>🔵 Facebook: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.facebook.com\u002Fsuperdev.school.th\">\u003Cstrong>Superdev School &nbsp;(Superdev)\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp>\u003Cstrong>📸 Instagram: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.instagram.com\u002Fsuperdevschool\u002F\">\u003Cstrong>superdevschool\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp>\u003Cstrong>🎬 TikTok: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.tiktok.com\u002F@superdevschool\">\u003Cstrong>superdevschool\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp class=\"\" data-start=\"5978\" data-end=\"6095\">\u003Cstrong>🌐 Website: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002F\">\u003Cstrong>www.superdev.school\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>","131_11zon_77s3oiys5m.webp","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclblg987654321\u002F1c6l9q9uy7orgo4\u002F131_11zon_77s3oiys5m.webp","2026-03-04 08:46:59.116Z","",{"keywords":15,"locale":43,"school_blog":53},[16,23,28,33,38],{"collectionId":17,"collectionName":18,"created":19,"created_by":13,"id":20,"name":21,"updated":22,"updated_by":13},"sclkey987654321","school_keywords","2026-03-04 08:20:11.547Z","ey3puyme01a9bsw","Go","2026-04-10 16:07:25.893Z",{"collectionId":17,"collectionName":18,"created":24,"created_by":13,"id":25,"name":26,"updated":27,"updated_by":13},"2026-03-04 08:20:14.253Z","ah6lvy4x8qe08l5","Golang","2026-04-10 16:07:26.172Z",{"collectionId":17,"collectionName":18,"created":29,"created_by":13,"id":30,"name":31,"updated":32,"updated_by":13},"2026-03-04 08:34:00.920Z","ecac9y661or1xka","WebSocket","2026-04-10 16:08:05.227Z",{"collectionId":17,"collectionName":18,"created":34,"created_by":13,"id":35,"name":36,"updated":37,"updated_by":13},"2026-03-04 08:46:51.136Z","rbaifonz0tg1ehh","ระบบแชท","2026-04-10 16:13:20.059Z",{"collectionId":17,"collectionName":18,"created":39,"created_by":13,"id":40,"name":41,"updated":42,"updated_by":13},"2026-03-04 08:44:37.391Z","krqs9dt45y5ixau","Connection Management","2026-04-10 16:12:47.710Z",{"code":44,"collectionId":45,"collectionName":46,"created":47,"flag":48,"id":49,"is_default":50,"label":51,"updated":52},"th","pbc_1989393366","locales","2026-01-22 10:59:55.832Z","twemoji:flag-thailand","s8wri3bt4vgg2ji",true,"Thai","2026-04-10 15:42:46.614Z",{"category":54,"collectionId":55,"collectionName":56,"expand":57,"id":71,"views":72},"wqxt7ag2gn7xcmk","pbc_2105096300","school_blogs",{"category":58},{"blogIds":59,"collectionId":60,"collectionName":61,"created":62,"created_by":13,"id":54,"image":63,"image_alt":13,"image_path":64,"label":65,"name":66,"priority":67,"publish_at":68,"scheduled_at":13,"status":69,"updated":70,"updated_by":13},[],"sclcatblg987654321","school_category_blogs","2026-03-04 08:33:53.210Z","59ty92ns80w_15oc1implw.png","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclcatblg987654321\u002Fwqxt7ag2gn7xcmk\u002F59ty92ns80w_15oc1implw.png",{"en":66,"th":66},"Golang The Series",1,"2026-03-16 04:39:38.440Z","published","2026-04-25 02:32:15.470Z","sxza010k0ci2mzn",244,"1c6l9q9uy7orgo4",[20,25,30,35,40],"2025-08-26 02:34:42.504Z","เรียนรู้การจัดการ Connection ในระบบ WebSocket Chat อย่างมีประสิทธิภาพด้วยภาษา Go ตั้งแต่การเพิ่ม-ลบผู้ใช้งาน ไปจนถึงการส่งข้อความแบบเฉพาะเจาะจงและ broadcast เพื่อให้รองรับผู้ใช้จำนวนมากได้อย่างมั่นคง","golang-websocket-connection-management","2026-04-25 02:48:11.123Z",{"th":77}]