如何使用signalr处理服务器上的客户端连接

时间:2013-10-31 20:34:34

标签: connection signalr

我有一个winform桌面应用程序。我引用了signalr.client并启动了与服务器的连接。我在connection_stateChanged()事件中收到了连接消息。

我的困难是:我在哪里捕获/添加客户端连接在我的服务器代码中?我需要添加任何客户端连接,然后我将把fileSystemWatcher放在特定于该connectionid的目录上。然后当文件进来时(在我的服务器上)我想通知我的.net客户端这个文件。完成后我希望我的客户端重新连接以通过相同的标准接收更多消息。

这是我到目前为止所做的:

[ServerCode] 在Global.asax.cs页面中:

  protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapConnection<ClientListener>("echo", "/echo");
    }

在我的App_code文件夹中的一个类中:

[

HubName("MotionIQ")]
public class ClientListener : Hub
{
    static ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();

    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }

    public void sendToSpecific(string name, string message, string to)
    {
        // Call the broadcastMessage method to update clients.
        Clients.Caller.broadcastMessage(name, message);
        Clients.Client(dic[to]).broadcastMessage(name, message);
    }

    public void Notify(string name, string id)
    {
        if (dic.ContainsKey(name))
        {
            Clients.Caller.differentName();
        }
        else
        {
            dic.TryAdd(name, id);

            foreach (KeyValuePair<String, String> entry in dic)
            {
                Clients.Caller.online(entry.Key);
            }

            Clients.Others.enters(name);
        }
    }

    public override Task OnDisconnected()
    {
        var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
        string s;
        dic.TryRemove(name.Key, out s);
        return Clients.All.disconnected(name.Key);
  }

[在我的.net c#桌面客户端应用程序中]

public void Init(bool _isLocal)
{
    var connection = new Connection("http://www.informedmotion.co.uk:12722/echo");//MotionIQ");
    connection.Received += new Action<string>(connection_Received);
    connection.StateChanged += new Action<StateChange>(connection_StateChanged);
    // Start the connection
    connection.Start().Wait();
    string line = null;
    while ((line = Console.ReadLine()) != null)
    {
        // Send a message to the server
        connection.Send(line).Wait();
    }
}
void connection_StateChanged(StateChange obj)
{

}

void connection_Received(string obj)
{

}

我几乎在那里,或者我做错了什么?

1 个答案:

答案 0 :(得分:2)

除非有令人信服的理由使用PersistentConnection,否则建议使用Hubs。

这是关于处理Hub类事件的文档:

http://www.asp.net/signalr/overview/signalr-20/hubs-api/handling-connection-lifetime-events