Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web;
- using Microsoft.AspNet.SignalR;
- using Microsoft.AspNet.SignalR.Hubs;
- namespace MultiEditWithSignalRv2.SignalR
- {
- [HubName("blogHub")]
- public class BlogHub : Hub
- {
- protected static ConcurrentDictionary<string, string> connectionGroups = new ConcurrentDictionary<string, string>();
- /// <summary>
- /// The method called from SignalR client (JS)
- /// </summary>
- /// <param name="message">String Data</param>
- /// <param name="append">A boolean value indicating
- /// if incoming value should be appended or overwritten
- /// when sent back to other clients</param>
- public void Send(string message, bool append = true)
- {
- // communicate only with group of clients
- // Clients.Group("group-name").ClientMethod();
- if (connectionGroups.TryGetValue(Context.ConnectionId, out string groupName))
- {
- // send the update to everyone in the group except the caller
- Clients.OthersInGroup(groupName).UpdateMessage(message, append);
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="groupName"></param>
- public void JoinGroup(string groupName)
- {
- var joinedGroup = connectionGroups.AddOrUpdate(Context.ConnectionId, groupName,
- (key, existingVal) =>
- {
- // If this delegate is invoked, then the key already exists.
- Groups.Remove(key, existingVal);
- return groupName;
- });
- Groups.Add(Context.ConnectionId, joinedGroup);
- // let this connection know they've joined the group
- Clients.Client(Context.ConnectionId).JoinedGroup(joinedGroup);
- // request an update from everyone else in the group
- Clients.OthersInGroup(joinedGroup).InitializeNewMember(Context.User.Identity.IsAuthenticated ?
- Context.User.Identity.Name :
- null);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="userName"></param>
- /// <param name="xPos"></param>
- /// <param name="yPos"></param>
- public void MouseMove(string userName, int xPos, int yPos)
- {
- if (connectionGroups.TryGetValue(Context.ConnectionId, out string groupName))
- {
- // send the update to everyone in the group except the caller
- Clients.OthersInGroup(groupName).MouseMove(userName, xPos, yPos);
- }
- }
- /// <summary>
- ///
- /// </summary>
- public void LeaveGroup()
- {
- if (connectionGroups.TryRemove(Context.ConnectionId, out string groupName))
- {
- Groups.Remove(Context.ConnectionId, groupName);
- }
- }
- public override Task OnConnected()
- {
- JoinGroup(Context.ConnectionId);
- return base.OnConnected();
- }
- public override Task OnDisconnected(bool stopCalled)
- {
- LeaveGroup();
- return base.OnDisconnected(stopCalled);
- }
- }
- }
Add Comment
Please, Sign In to add comment