- SignalRChatRoom.zip
- SignalRChatRoom
- packages
- jQuery.1.8.2
- Microsoft.AspNet.SignalR.1.0.0
- Microsoft.AspNet.SignalR.Core.1.0.0
- Microsoft.AspNet.SignalR.JS.1.0.0
- Microsoft.AspNet.SignalR.Owin.1.0.0
- Microsoft.AspNet.SignalR.SystemWeb.1.0.0
- Microsoft.Owin.Host.SystemWeb.1.0.0
- Microsoft.Web.Infrastructure.1.0.0.0
- Newtonsoft.Json.4.5.11
- lib
- net20
- net35
- net40
- portable-net40%2Bsl4%2Bwp7%2Bwin8
- sl3-wp
- sl4
- sl4-windowsphone71
- winrt45
- Newtonsoft.Json.4.5.11.nupkg
- Newtonsoft.Json.4.5.11.nuspec
- Owin.1.0
- repositories.config
- SignalRChat.sln
- SignalRChat.v11.suo
- SignalRChat
- SignalRChatRoom-noexe.zip
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using SignalRChat.Common;
namespace SignalRChat
{
public class ChatHub : Hub
{
#region Data Members
static List<UserDetail> ConnectedUsers = new List<UserDetail>();
static List<MessageDetail> CurrentMessage = new List<MessageDetail>();
#endregion
#region Methods
public void Connect(string userName)
{
var id = Context.ConnectionId;
if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
{
ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName });
// send to caller
Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);
// send to all except caller client
Clients.AllExcept(id).onNewUserConnected(id, userName);
}
}
public void SendMessageToAll(string userName, string message)
{
// store last 100 messages in cache
AddMessageinCache(userName, message);
// Broad cast message
Clients.All.messageReceived(userName, message);
}
public void SendPrivateMessage(string toUserId, string message)
{
string fromUserId = Context.ConnectionId;
var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ;
var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
if (toUser != null && fromUser!=null)
{
// send to
Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message);
// send to caller user
Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
}
}
public override System.Threading.Tasks.Task OnDisconnected()
{
var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
if (item != null)
{
ConnectedUsers.Remove(item);
var id = Context.ConnectionId;
Clients.All.onUserDisconnected(id, item.UserName);
}
return base.OnDisconnected();
}
#endregion
#region private Messages
private void AddMessageinCache(string userName, string message)
{
CurrentMessage.Add(new MessageDetail { UserName = userName, Message = message });
if (CurrentMessage.Count > 100)
CurrentMessage.RemoveAt(0);
}
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.