5
我正在測試SignalR(0.4.0 via nuget)並且找不到任何方式讓服務器強制斷開客戶端連接。我想我錯過了一些明顯的東西。如何強制斷開SignalR中的客戶端
我的測試代碼在下面,我已經在幾乎每個地方都嘗試過Close()和Timeout(),並且我可以想象它們沒有成功。客戶端繼續接收脈衝的消息,雖然我總是出現在來自return Connection.Close()
第4-5秒內得到2重新連接OnReceivedAsync()
服務器:
internal class SignalRServer
{
private Server server;
public SignalRServer()
{
server = new Server("http://localhost:13170/");
server.MapConnection<EchoConnection>("/echo");
server.Start();
Timer timer = new Timer(1000);
timer.Elapsed += OnTimer;
timer.Enabled = true;
}
void OnTimer(object sender, ElapsedEventArgs e)
{
IConnectionManager manager = server.DependencyResolver.GetService(typeof(IConnectionManager)) as IConnectionManager;
IConnection connection = manager.GetConnection<EchoConnection>();
connection.Broadcast("pulse");
connection.Close();
connection.Timeout();
}
}
internal class EchoConnection : PersistentConnection
{
protected override Task OnConnectedAsync(IRequest request, IEnumerable<string> groups, string connectionId)
{
Connection.Timeout();
Connection.Close();
return Connection.Broadcast(String.Format("{0} connection", connectionId));
}
protected override Task OnReconnectedAsync(IRequest request, IEnumerable<string> groups, string connectionId)
{
return Connection.Broadcast(String.Format("{0} reconnection", connectionId));
}
protected override Task OnReceivedAsync(string connectionId, string data)
{
Console.WriteLine(data);
Connection.Close();
Connection.Timeout();
Connection.Broadcast(data);
return Connection.Close();
}
}
客戶:
internal class SignalRClient
{
private readonly Connection connection;
public SignalRClient()
{
connection = new Connection("http://localhost:13170/echo");
connection.Received += OnReceive;
connection.Closed += OnClosed;
connection
.Start()
.ContinueWith(t =>
{
if (!t.IsFaulted)
connection.Send("Hello");
else
Console.WriteLine(t.Exception);
});
Console.WriteLine(connection.ConnectionId);
}
void OnClosed()
{
// never called
connection.Stop();
}
void OnReceive(string data)
{
Console.WriteLine(data);
}
}
示例客戶端輸出:
d7615b15-f80c-4bc5-b37b-223ef 96fe96c連接
你好
脈衝
脈衝
d7615b15-f80c-4bc5-b37b-223ef96fe96c重新連接
脈衝
脈衝
d7615b15-f80c-4bc5-b37b-223ef96fe96c重新連接
脈衝
脈衝
脈衝
脈衝
脈衝
脈衝
...
謝謝,這將工作,但我很驚訝沒有什麼內置的來源。 Close()方法建議它向客戶端發送消息以斷開連接,但我無法實際實現。 – Adster 2012-02-22 11:26:41
這是.net客戶端中的一個錯誤。你爲什麼試圖強迫連接關閉? – davidfowl 2012-02-22 21:46:54
@dfowler我正在構建一個代理應用程序,位於現有基於套接字的服務器和移動Web客戶端之間。如果套接字在服務器上關閉,我想將該斷開連接轉發給客戶端。我現在要和nmat的建議一起去,並且當我有一個真正的JS客戶端進行測試時再次測試close()。乾杯 – Adster 2012-02-23 10:19:41