ลองทำ Web Realtime Syncด้วย ASP.NET SignalR

best0032001
Sep 6, 2018 · 2 min read

ถ้าใครใช้ Facebook web เป็นประจำก็จะทราบว่า Facebook web นั้นมีการ
Realtime Sync ตลอดเวลา เมื่อมีคน comment post ของคุณ หน้าweb ก็จะ update เอง auto โดยที่ไม่ต้องกด Refresh web ตัวอย่าง Blog วันนี้จะมาลองพัฒนา
Web Realtime Sync ASP.NET SignalR https://www.asp.net/signalr
ซึ่ง สามารถใช้ กับ .net framework
ส่วนใครสาย open source จะ run บน linux ก็ไม่ต้องห่วงเพราะว่า
ASP.NET SignalR มีบน .net core version เหมือนกัน
การทำงานก็เหมือนกัน

สำหรับ how to ในครั้งนี้ เดียวผมจะทำการ update Source บน Github เพื่อเป็น Code ตัวอย่าง ในนักพพัฒนาได้เอาไปศึกษาต่อยอดกับงาน

Part1 ตัวอย่างการทำงาน

ตัวอย่าง หน้าแรกคือ หน้าที่เราจะทำการ Register ระบุว่า ใครเป็นคนที่ใช้ Browser
อาจจะเป็น User ID ของweb นั้นๆ

พอ user กด Register ตัว SignalR จะทำการ สร้าง ConnectionId ส่งไปที่ server
ซึ่งในส่วนของServer Logic ก็จะทำการ เก็บค่า UserID คู่กับ ConnectionId
แล้วบันทึกลง ในหน่วยความจำเพื่อเรียกใช้ต่อไป

จากนั้นลองส่ง ข้อความ โดนระบุว่าส่งไปให้ UserID ไหน สิ่งที่เกิดขึ้นหลังบ้าน
สิ่งที่เกิดขึ้น เราจะให้ Controller home รับค่า Who และ test(Text)
จะทำการ เอา who คือ userid ไปหาใน cache ที่บันทึกไว้เพื่อหา ConnectionId แล้วส่งไป ซึ่งหน้า page 1 ก็จะ update ข้อความที่ส่งมาแบบ auto

เพื่อไม่ให้ blog ยาวเกินไป เดียววิธีเขียน จะเป็น Blog ถัดไป

    best0032001

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade