2014年4月5日 星期六

SignalR2.0 實作聊天室上線清單

繼上一篇聊天室做好之後,再來加一下聊天清單

http://tsengpm.blogspot.tw/2014/04/mvc4-signalr-chat-signalr-20.html

其實就是改一下ChatHub.cs這個檔案

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public static ConcurrentDictionary<string, UserData> UserList = new ConcurrentDictionary<string, UserData>();

        //離開時刪除ID
        public override Task OnDisconnected()
        {
            UserData Value;
            UserList.TryRemove(Context.ConnectionId, out Value);

            return Clients.All.showConnected(UserList);
        }
        public void GetUsers()
        {
            Clients.All.showConnected(UserList);
        }
        //進入時加入ID
        public void Join(UserData data)
        {
            data.Connected = DateTime.Now.ToString("f");
            UserList.TryAdd(Context.ConnectionId, data);
            Clients.All.showConnected(UserList);
        }
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.broadcastMessage(name, message);
        }   
    }
    public class UserData
    {
        public int Sid { get; set; }
        public string Connected { get; set; }
        public string Name { get; set; }

    }
}

另外在頁面上的start也要調整

$.connection.hub.start().done(function () {
 $('#sendmessage').click(function () {
  
  chat.server.join({ Sid: $('#displayId').val(), Name: $('#displayName').val() }).done(function () {
   chat.server.getUsers();
  });
 });
});

接著在頁面上放一個userList的 ul控制項,然後Key入以下的程式碼,他就會一直append了

chat.client.showConnected = function (userList) {
            $.each(userList, function (index, data) {               
                $("#userList").append("<li>" + data.Name + "</li>");
            });
        };

沒有留言:

張貼留言