跳到主要內容

SignalR Online User Count

線上人數: 2
  • id:5f35694c-e0a5-4b31-8239-9ccd48cf23fb
    ip:992.168.0.3
    Url:http://localhost:57987/onLineCount.aspx
    Brower:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.189 Safari/537.36 Vivaldi/1.95.1077.60

  • id:1597b783-5591-4073-ac93-1f8d4ec8e565
    ip:892.168.5.3
    Url:http://localhost:57987/onLineCount.aspx
    Brower:Mozilla/5.0 (Windows NT 6.1; rv:59.0) Gecko/20100101 Firefox/59.0


-----------------------------------------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

//路由組態


[assembly: OwinStartup(typeof(SignalRTest.Startup))]

namespace SignalRTest
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 如需如何設定應用程式的詳細資訊,請參閱  http://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();

        }
    }
}



-----------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRTest
{
    public class UserData
    {

        public string id
        {
            get;
            set;
        }
        public string ip
        {
            get;
            set;
        }

        public string url
        {
            get;
            set;
        }

        public string browser
        {
            get;
            set;
        }


    }
}

-----------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace SignalRTest
{
    public class CountHub : Hub
    {

        //目前所有連線的list
        static List<UserData> UserDataList = new List<UserData>(0);

        public void userConnected(string pUrl, string pBrowser)
        {
            //使用者連線 加入清單
            var query = from u in UserDataList
                        where u.id == Context.ConnectionId
                        select u;

            if (query.Count() == 0)
            {   //這段自由發揮
                UserDataList.Add(new UserData
                {
                    id = Context.ConnectionId,
                    ip = GetLocalIPAddress(),
                    url = pUrl,
                    browser = pBrowser
                });
            }
            Clients.All.getList(UserDataList);   //呼叫前端function
        }


        public override Task OnDisconnected(bool stopCalled)
        {
            //離開時清除清單
            Clients.All.removeList(Context.ConnectionId);

            var item = UserDataList.FirstOrDefault(x => x.id == Context.ConnectionId);
            if (item != null)
            {
                UserDataList.Remove(item);   //刪除             
                Clients.All.onUserDisconnected(item.id);  //呼叫前端function     
            }
            return base.OnDisconnected(stopCalled);
        }


        public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }


    }
}


-----------------------------------------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="onLineCount.aspx.cs" Inherits="SignalRTest.onLineCount" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>

    <script src="Scripts/jquery-1.6.4.min.js"></script> 
    <script src="Scripts/jquery.signalR-2.2.3.min.js"></script> 
    <script src="/signalr/hubs"></script>

</head>


<body>
    <form id="form1" runat="server">
 
        線上人數: <span id="spanCountUser"></span>
        <div>
                <ul id="listUserData"></ul>
        </div>


        <script type="text/javascript">
            var countUserNum = 0;

            $(function () {
                //建立與Server端的Hub的物件,注意Hub的開頭字母一定要為小寫
                var onlineHub = $.connection.countHub;

                //將連線打開
                $.connection.hub.start().done(function () {
                    onlineHub.server.userConnected(location.href, navigator.userAgent); //呼叫server
                });


                //讓server呼叫(抓取資料)
                onlineHub.client.getList = function (UserDataList) {

                    //內容自由發揮
                    var HasObj = $('#listUserData');
                    if (!HasObj.length)
                        return;

                    $("#listUserData").html("");
                    var li = "";
                    $.each(UserDataList, function (index, data) {
                        li += "<li id='" + data.id + "'> id:" + data.id + "<br> ip:" + data.ip + "<br> Url:" + data.url + "<br> Brower:" + data.browser + "</li> <p/>";
                    });
                    $("#listUserData").html(li);

                    countUserNum = UserDataList.length;
                    $("#spanCountUser").text(countUserNum);
                }


                //讓server呼叫(移除離開人員)
                onlineHub.client.onUserDisconnected = function (id) {
                    //內容自由發揮
                    $('#' + id).remove();

                    if (countUserNum > 0) {
                        countUserNum = countUserNum - 1;
                        $("#spanCountUser").text(countUserNum);
                    }
                }

            });

        </script>


    </form>
</body>
</html>