如何强制断开SignalR中的客户端

时间:2012-02-21 17:23:44

标签: c# signalr

我正在测试SignalR(0.4.0通过nuget),并且找不到任何方法让服务器强行断开客户端。我想我错过了一些明显的东西。

我的测试代码在下面,我已经尝试了几乎所有地方和组合的Close()和Timeout(),我没想到也没有成功。客户端继续接收脉冲消息,但我总是在前{4-}秒内return Connection.Close() 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(); } } 内重新连接2次

服务器:

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);
    }
}

客户端:

{{1}}

示例客户端输出:

  

d7615b15-f80c-4bc5-b37b-223ef96fe96c连接
  你好
  脉冲
  脉冲
  d7615b15-f80c-4bc5-b37b-223ef96fe96c重新连接
  脉冲
  脉冲
  d7615b15-f80c-4bc5-b37b-223ef96fe96c重新连接
  脉冲
  脉冲
  脉冲
  脉冲
  脉冲
  脉冲
  ...

2 个答案:

答案 0 :(得分:2)

将特定字符串发送到客户端以强制断开连接:

void OnReceive(string data)
{
    if(data.Equals("exit"))
    {
        connection.Stop();
        return;
    }

    Console.WriteLine(data);
}

答案 1 :(得分:1)