我正在使用SignalR在网站上传输数据。但是SignalR只能在一段时间内发送数据,如果时间已过,则应该关闭连接。
如果一个请求仍处于挂起状态且尚未完成,则$.connection.hub.stop()
停止函数将被取消。但是,无论发送了多少数据,此请求应该被强制取消。
如何关闭SignalR连接?
我正在使用SignalR在网站上传输数据。但是SignalR只能在一段时间内发送数据,如果时间已过,则应该关闭连接。
如果一个请求仍处于挂起状态且尚未完成,则$.connection.hub.stop()
停止函数将被取消。但是,无论发送了多少数据,此请求应该被强制取消。
如何关闭SignalR连接?
protected void Application_Start(object sender, EventArgs e)
{
// Make long-polling connections wait a maximum of 110 seconds for a
// response. When that time expires, trigger a timeout command and
// make the client reconnect.
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110);
// Wait a maximum of 30 seconds after a transport connection is lost
// before raising the Disconnected event to terminate the SignalR connection.
GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);
// For transports other than long polling, send a keepalive packet every
// 10 seconds.
// This value must be no more than 1/3 of the DisconnectTimeout value.
GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);
RouteTable.Routes.MapHubs();
}
编辑:既然您想无论如何都要从客户端断开连接,那么您正在讨论一个CancellationToken
行为,但不幸的是,这在SignalR中仍然不受支持,正如您可以在这里和这里看到的那样,团队想要将其添加到SignalR
中,但目前还没有相关消息。
Global.asax
文件的Application_Start
中设置它们。但是这种方式不能完全控制客户端。因此,当新用户连接时,您需要使用javascript setTimeout
函数并传递时间表单服务器端。它可能是GlobalHost.Configuration.DisconnectTimeout
或您想要的任何时间。我在一个非常大的实时票务系统中使用此逻辑来进行实时持票。(请阅读所有内联注释)
模型:
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public static string Send(MyModel my)
{
//Do Somthing
return $"Data Sending to {my.Name}...";
}
public static string Stop(string name)
{
//Do Somthing
return $"ForceStop {name}.";
}
public static string Delete()
{
//Do Somthing
return "Deleted";
}
}
中心:
[HubName("myHub")]
public class MyHub : Hub
{
int connectionTimeOut = 10;//sec
[HubMethodName("connect")]
public void Connect()
{
//apply logic if any when user connected or reload page
//set connection Time Out as you need
connectionTimeOut= 10;// GlobalHost.Configuration.DisconnectTimeout
Clients.Client(Context.ConnectionId).onNewUserConnected(connectionTimeOut);
}
[HubMethodName("startSendingServer")]
public void StartSending(int id, string name)//pass anything you need
{
//apply logic if any when start sending data
var my = new MyModel
{
Id = id,
Name = name
};
var status = MyModel.Send(my);//example
var result = new
{
status,
name
};
Clients.Client(Context.ConnectionId).startSendingClient(result);
}
[HubMethodName("forceStopServer")]
public void ForceStop(string name)//pass anything you need
{
//apply logic if any when force stop sending data
var status = MyModel.Stop(name);
Clients.Client(Context.ConnectionId).forceStopClint(status);
}
public override Task OnDisconnected(bool stopCalled)
{
//apply logic if any when connection Disconnected
var status = MyModel.Delete();//example
if (stopCalled)
{
// status=String.Format("Client {0} explicitly closed the connection.", Context.ConnectionId)
//your code here
}
else
{
// status=String.Format("Client {0} timed out .", Context.ConnectionId);
//your code here
//Clients.Client(Context.ConnectionId).onUserDisconnected(status);
}
return base.OnDisconnected(stopCalled);
}
}
<div class="row">
<div class="col-md-12">
<h1> Status: <span id="hubStatus"></span></h1>
<br />
<h4> Countdown : <span id="counter"></span></h4>
<br />
<button id="btnHub" class="btn btn-primary btn-lg">Start Sending Data</button>
</div>
</div>
@section scripts{
<script src="~/Scripts/app/hub.js"></script>
}
hub.js:
var proxyTimer = null;
var sendTimeLimit = 1;//sec
var sessionTime = sendTimeLimit * 1000;
$(function () {
var myProxy = $.connection.myHub;
$.connection.hub.start().done(function () {
registerServerEvents(myProxy);
});
clientMethods(myProxy);
});
function registerServerEvents(proxyHub) {
proxyHub.server.connect();
$(document).on("click", "#btnHub", function (e) {
$("#hubStatus").html("Sending..");
$("#btnHub").text("Count Down Start...");
//Logic Before start sending data.
var id = 1;
var name = "AzR";
proxyHub.server.startSendingServer(id,name);
// $.connection.hub.disconnected(function () {
// setTimeout(function () { $.connection.hub.start(); }, 5000); // Restart connection after 5 seconds.
//});
$.connection.hub.disconnected(function () {
$("#hubStatus").html("Disconnected");// you can restart on here.
$("#btnHub").text("Stat Again after reload window");
});
});
}
function clientMethods(proxyHub) {
//proxyHub.on('onConnected', function (sendTimeLimit) {
// sendTimeLimit = sendTimeLimit;
//});
proxyHub.on('onNewUserConnected', function (serverItem) {
sendTimeLimit = serverItem;
sessionTime = sendTimeLimit * 1000;
});
proxyHub.on('startSendingClient', function (serverItem) {
//Logic after start sending data.
var name = serverItem.name;
var status = serverItem.status;
$("#hubStatus").html(status);
$("#counter").html(sendTimeLimit);
timeCounter();
startTimer(proxyHub, name );
});
proxyHub.on('forceStopClint', function (serverItem) {
clearClintPendingTask(serverItem);//Logic before proxy stop.
$("#btnHub").text("Force Stop...");
$.connection.hub.stop();
});
proxyHub.on('onUserDisconnected', function (serverItem) {
//Logic after proxy Disconnected (time out).
$("#hubStatus").html(serverItem);
$("#btnHub").text("Stat Again after reload window");
});
}
//Logic before proxy stop.
function clearClintPendingTask(status) {
//do all you need
$("#hubStatus").html(status);
stopTimer();
}
function startTimer(proxyHub,data) {
stopTimer();
proxyTimer = setTimeout(function () {
proxyHub.server.forceStopServer(data);
}, sessionTime);
}
function stopTimer() {
if (proxyTimer) {
clearTimeout(proxyTimer);
proxyTimer = null;
}
}
function timeCounter() {
var counter = sendTimeLimit;
var interval = setInterval(function () {
counter--;
$("#counter").html(counter);
if (counter == 0) {
//Do something
$("#counter").html("Countdown ended!");
// Stop the counter
clearInterval(interval);
}
}, 1000);
}
您需要定义一个超时时间。在服务器上,您可以设置DisconnectTimeout,例如:
GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromMinutes(30);
https://zzz.buzz/2016/05/11/setting-timeout-for-signalr-for-easier-debugging/
更新编辑,请参见下面的选项3。 其他所有方法都依赖于超时,我发布了一个强制断开连接。
如果您正在尝试强制断开连接-您可以获取已连接用户列表并在服务器端调用ForceLogOut
函数,我在某个代码项目中看到了这个,希望它有所帮助。 如果您只想强制注销/终止某些用户,则只需循环并仅终止该连接即可。
服务器端
public class User
{
public string Name { get; set; }
public HashSet<string> ConnectionIds { get; set; }
}
public class ExtendedHub : Hub
{
private static readonly ConcurrentDictionary<string, User> ActiveUsers =
new ConcurrentDictionary<string, User>(StringComparer.InvariantCultureIgnoreCase);
public IEnumerable<string> GetConnectedUsers()
{
return ActiveUsers.Where(x => {
lock (x.Value.ConnectionIds)
{
return !x.Value.ConnectionIds.Contains
(Context.ConnectionId, StringComparer.InvariantCultureIgnoreCase);
}
}).Select(x => x.Key);
}
public void forceLogOut(string to)
{
User receiver;
if (ActiveUsers.TryGetValue(to, out receiver))
{
IEnumerable<string> allReceivers;
lock (receiver.ConnectionIds)
{
allReceivers = receiver.ConnectionIds.Concat(receiver.ConnectionIds);
}
foreach (var cid in allReceivers)
{
// ***************** log out/KILL connection for whom ever your want here
Clients.Client(cid).Signout();
}
}
}
}
客户端
// 1- Save your connection variable when you start it, and later on you can use it to stop.
var myHubProxy = $.connection.myHub
// 2- Use it when you need to stop it, IF NOT YOU WILL GET AN ERROR
myHubProxy.client.stopClient = function() {
$.connection.hub.stop();
};
// With a button for testing
$('#SomeButtonKillSignalr').click(function () {
$.connection.hub.stop();
});
选项3已更新:根据请求...其他解决方案依赖于超时,但您也可以通过自己处理连接来直接强制关闭
我打开了SignalR代码,在其中您可以看到DisposeAndRemoveAsync
是客户端连接的实际终止。
1- 您可以修改或调用DisposeAndRemoveAsync
与您的连接一起使用。
2- 然后调用RemoveConnection(connection.ConnectionId);
public async Task DisposeAndRemoveAsync(HttpConnectionContext connection)
{
try
{
// this will force it
await connection.DisposeAsync();
}
catch (IOException ex)
{
_logger.ConnectionReset(connection.ConnectionId, ex);
}
catch (WebSocketException ex) when (ex.InnerException is IOException)
{
_logger.ConnectionReset(connection.ConnectionId, ex);
}
catch (Exception ex)
{
_logger.FailedDispose(connection.ConnectionId, ex);
}
finally
{
// Remove it from the list after disposal so that's it's easy to see
// connections that might be in a hung state via the connections list
RemoveConnection(connection.ConnectionId);
}
}
注意,当完成时请自行清理。
$.connection.hub.stop()
函数会抛出一个错误,因为请求尚未完全发送到后端。因此,我正在寻找一种解决方案,即使存在正在运行的请求,也可以终止当前活动的连接。 - Snickbrack