WCF duplex TCP communication error

岁酱吖の 提交于 2019-12-06 08:50:13

When a client calls SubcribeToService you add its operation context to a List called JoinedClien.

When you call Broadcast in your server, you call the method NotifyClient on all collected operation contexts for every client that has ever connected.

The problem is, that a disconnected client won't get removed from your JoinedClien list. When you try to call an operation method on a disconnected operation context, you get the channel is in faulted state error.

To work around, you should subscribe to the Channel_Closed and Channel_Faulted events and also catch the CommunicationException when calling back into your clients and remove the operation context of the faulted clients:

public void Broadcast(string message)
{
    // copy list of clients
    List<OperationContext> clientsCopy = new List<OperationContext>();
    lock(JoinedClien) {
        clientsCopy.AddRange(JoinedClien);
    }

    // send message and collect faulted clients in separate list
    List<OperationContext> clientsToRemove = new List<OperationContext>();
    foreach (var c in JoinedClien) 
    { 
        try {
            c.NotifyClient("message was received " + message));
        }
        catch (CommunicationException ex) {
            clientsToRemove.Add(c);
        }
    }

    foreach (var c in clientsToRemove)
    {
        lock(JoinedClien) {
            if(JoinedClien.Contains(c))
                JoinedClien.Remove(c);
        }
    }
}

When adding new clients you have to lock that operation, too:

var subscriber = OperationContext.Current.GetCallbackChannel<ISampleServiceCallBack>();
lock(JoinedClien) 
{
    if (!JoinedClien.Contains(subscriber))
    {
        JoinedClien.Add(subscriber);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!