I want to implement single session enforcement in my application. Meaning if another login activity found for the same user in different browser/different machine then then first session should get auto logoff. If I use the Ajax polling then unnecessary network traffic will happen. So am planning to use signalR.
For that i tried simple click event. Its working without refreshing the page from browser 1 to browser 2.
I created hubclass and my cshtml as follows
var myHub = $.connection.myHub;
$.connection.hub.logging = true;
$.connection.hub.start();
myHub.client.Postmessage = function (message) {
$('#message1').append('<li><strong>'+ htmlEncode(messaage) + '</li>')
$("btnClick").click(function () (
var message = $('message').val();
myHub.server.helloServer(message);
$('#message1').val('').focus();
External service class to find the session details
private static ISSEnforcementSvc ssEnforcement;
public static SSEnforcementSVC GetSSEnforcementService()
{
if (ssEnforcement == null)
{
var localService GetLocalizationsvc;
var configurationSvc = GetConfigurationSvc();
var cacheSvc = GetCacheSvc();
ssessionEnforcement Service = new
SinglesessionEnforcementService(localService,
configurationSvc,cacheSvc)
}
return ssEnforcement;
}
Please suggest how to implement same way to push the 1st browser to logoff.
i have stored some client data on server in datagrid using signalr (whenever client connects details of all clients updated on server like ipaddress, name etc)... so i want to send that datagrid details to all clients and the condition is whenever new clients connect to server then all client including current client must get updated list ....here is my code basically what i have done till now,
public override Task OnConnected()
{
object ipaddress;
var a=Context.QueryString["name"];
var b= Context.QueryString["AnotherValue"];
if (Context.Request.Environment.TryGetValue("server.RemoteIpAddress", out ipaddress))
{
//ipcollections = new List<string[]>();
userhandler.ipcol.Add(new string[] { ipaddress.ToString(), a, b });
Program.MainForm.writetodatagrid(userhandler.ipcol);
}
Program.MainForm.WriteToConsole("Client connected: " + Context.ConnectionId );
return base.OnConnected();
}
and showing this list on server itself in datagird...i have to send this list to all clients...please help me...thank you....or is there any other way or am i doing things wrong please tell me..
On the server you would have a Hub and a method on the Hub to broadcast.
public class MyHub : Hub
{
public void Send(string ipaddress, string name)
{
Clients.All.addMessage(ipaddress, name);
}
}
Take a look at the following post. It has a an example of what you would do on your winforms client.
https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b#content
and the source code for the winforms client:
https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b/sourcecode?fileId=119892&pathId=583880341
During development of HangFire application with C# ASP.NET, and I decided to implement functionally where Admin can manage state of Server, jobs.
List item
Server Enable Disable state. Using Enable Button click event Admin
can start JOB server so all the Fire and Forget and Recurrent job can
performed. And Disable button stop all the activities of JOB.
Retrieve the current state of Server
I want to retrieve current state of JOB server, So I can show is
server is on or Off.
Retrieve state and enable / disable state of Jobs (Only recurrent).
If you want to manage Server/Job created by Hangfire, you can use MonitoringApi or JobStorage to get there statuses.
Sample Codes :
var _jobStorage = JobStorage.Current;
// How to get recurringjobs
using (var connection = _jobStorage.GetConnection())
{
var storageConnection = connection as JobStorageConnection;
if (storageConnection != null)
{
var recurringJob = storageConnection.GetRecurringJobs();
foreach(var job in recurringJob)
{
// do you stuff
}
}
}
// How to get Servers
var monitoringApi = _jobStorage.GetMonitoringApi();
var serverList = monitoringApi.Servers();
foreach( var server in serverList)
{
// do you stuff with the server
// you can use var connection = _jobStorage.GetConnection()
// to remove server
}
From here you can play around with Hangfire.
I'm trying to get the connected user id in my signleR application but I didn't manage to find it. Is there any way to get it because I want when two users are chatting just the two of them will receive each other's messages and not the whole group they are connected to, or all clients connected to signleR hub. My main goal is to send private messages between two connected clients.
My code is so complicated but all I have found is how to broadcast my message to all the clients or to a specific group, but I couldn't manage to send a private message. I did this to send user typing message:
public void UserTyping(string msg, int ToClient) { // display User is Typing Msg
Clients.Others.OtherUserIsTyping(msg, ToClient);
}
ClientSide:
var keyPressCount = 0;
$("#<%=MsgToSend.ClientID %>").keypress(function () {
// Throttle the server call with some logic
// Don't want to call the server on every keypress
var ToClientID = $("#ToClientID").val();
if (keyPressCount++ % 10 == 0) {
chat.server.userTyping("Is typing...", ToClientID); // call the server side function
}
});
chat.client.OtherUserIsTyping = function (msg, ToClient) { // declare the function on the chat hub so the server can invoke it
$("#UserTyping").html(msg);
}
I want to create html5 web multiroom chat, based on HTML5 websocket.
But I need some little help to start.
I want to do server side code in c#, but I can not find any tutorials how to do chat websocket server with multi room in c#.
Is there any server which is already implemented in .net, or which I can update to multi room chat ?
It is a little project, one room for 10 peoples. Could you help to me how to start ?
Thank you very much !
I prepare example code structure:
Main server class:
class Program
{
// List of courses, which are currentli avalible ( REPRESENT CHAT ROOM)
protected static ConcurrentDictionary<Course, string> OnlineUsers = new ConcurrentDictionary<Course, string>();
static void Main(string[] args)
{
// Initialize the server on port 81, accept any IPs, and bind events.
var aServer = new WebSocketServer(81, IPAddress.Any)
{
OnReceive = OnReceive,
OnSend = OnSend,
OnConnected = OnConnect,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, 5, 0)
};
aServer.Start();
// Accept commands on the console and keep it alive
var command = string.Empty;
while (command != "exit")
{
command = Console.ReadLine();
}
aServer.Stop();
}
// event when the clients connect to server
// Server send to client list of Lessons which are avalible, after
private static void OnConnect(UserContext context)
{
throw new NotImplementedException();
}
// event whent the client, want to disconnect from server
private static void OnDisconnect(UserContext context)
{
throw new NotImplementedException();
}
// event, when client is sending some data
private static void OnSend(UserContext context)
{
throw new NotImplementedException();
}
// event, when server receive data from client
// client choose which room want to join and, we add cleint to list of lessons which he choose
// another method ... Register, Rename, LogOff ...
private static void OnReceive(UserContext context)
{
throw new NotImplementedException();
}
}
Course class: (ROOMS)
class Course
{
// Every course has list of active users
protected static ConcurrentDictionary<User, string> OnlineUsers = new ConcurrentDictionary<User, string>();
// Name of course
public String CourseName { get; set; }
}
User class:
class User
{
// Name of User
public string Name = String.Empty;
// UserContext - Contains data we will export to the Event Delegates.
public UserContext Context { get; set; }
}
It is good structure for my purpose ? I have many courses (room), with one teacher, in one course can be 20 pupils example .. In one course the pupils can talk with techer using chat (web socket) and drawing board ..
That's how I would build the object hierarchy:
The chat server should have a list of ChatRooms.
Each ChatRoom should have a list of ChatUsers.
Each ChatUser should have one or no ChatRoom and an outbound socket.
(this assumes that a user is only in one room at a time. Allowing multiple rooms would make things a bit more complex)
That's how room selection could work:
When a client connects, a ChatUser is created. The first thing the server does is send the list of chatrooms to the user. The client then responds with the name of the chatroom it wants to join. When a chatroom of that name doesn't exist, it is created and added to the global list of rooms.
The client is then added to the room, and the room is set on the client.
That's how chatting could work:
When the socket of the user receives a chat message, it should call a SendToAllClients method on the room the user is currently in (when the room is null, it should return an error message to the user that they must join a room first).
The SendToAll method of the room should then call a SendToClient of all users which are on its list of users.
The SendToClient method of the class would then send the chat message to the client.
How to expand this for multiple chatrooms per user
To allow a client to join multiple chatrooms at once and have separate conversations in them, the client must be able to:
request a list of rooms at any time, not just at startup
join rooms at any time, not just at startup
leave rooms
specify the room when sending a message
That means that the action the client wants to perform can not be deduced from the state it is currently in. You need to add this information to the messages of the user. You could, for example, do this as prefixes. Like
!list
requests the list of rooms
!join:asdf
join/create the room asdf
_asdf:Hello
sends the message Hello to the room asdf.
The messages from the server should have similar prefixes, so that the client can deduce if a message is a room list or a chat message and from what room it originates.
You should try to look into SignalR for ASP.NET (example : jabbr.net/). This may be more helpful and handy.