使用REST公开WCF回调

时间:2012-07-27 21:04:46

标签: c# vb.net wcf web-services

所以我有一个客户端应用程序和一个WCF服务发布到IIS服务器。我成功地让客户端订阅了WCF服务,然后在任意一个客户端上单击一个按钮后向客户端应用程序的每个实例发送一条消息。现在我的目标是从WCF应用程序中推出消息,但是通过Web浏览器中的REST,这将允许我在Android中使用此界面并在Android客户端和Windows客户端应用程序之间进行交互。任何人都知道我需要做什么?以下是我工作的界面的基础知识。

IService.vb:

    <ServiceContract(SessionMode:=SessionMode.Required, CallbackContract:=GetType(IServiceCallback))>
Public Interface IService
    <OperationContract(IsOneWay:=True)>
    Sub GetClientCount()

    <OperationContract(IsOneWay:=True)>
    Sub RegisterClient(ByVal id As Guid)

    <OperationContract(IsOneWay:=True)>
    Sub UnRegisterClient(ByVal id As Guid)
End Interface

Public Interface IServiceCallback
    <OperationContract(IsOneWay:=True)>
    Sub SendCount(ByVal count As Int32)
End Interface

Service.svc.vb

<ServiceBehavior(InstanceContextMode:=InstanceContextMode.Single, ConcurrencyMode:=ConcurrencyMode.Multiple)>
Public Class Service
    Implements IService, IRestService
    Private clients As New Dictionary(Of Client, IServiceCallback)()
    Private locker As New Object()

    Public ReadOnly Property Callback As IServiceCallback
        Get
            Return OperationContext.Current.GetCallbackChannel(Of IServiceCallback)()
        End Get
    End Property

    'called by clients to get count
    Public Sub GetClientCount() Implements IService.GetClientCount
        Dim query = ( _
        From c In clients _
        Select c.Value).ToList()

        Dim action As Action(Of IServiceCallback) = Function(Callback) GetCount(Callback)

        query.ForEach(action)
    End Sub

    Private Function GetCount(ByVal callback As IServiceCallback) As Int32
        callback.SendCount(clients.Count)
        Return Nothing
    End Function

    '---add a newly connected client to the dictionary---
    Public Sub RegisterClient(ByVal guid As Guid) Implements IService.RegisterClient
        '---prevent multiple clients adding at the same time---
        SyncLock locker
            clients.Add(New Client With {.id = guid}, Callback)
        End SyncLock
    End Sub

    '---unregister a client by removing its GUID from 
    ' dictionary---
    Public Sub UnRegisterClient(ByVal guid As Guid) Implements IService.UnRegisterClient
        Dim query = From c In clients.Keys _
                    Where c.id = guid _
                    Select c
        clients.Remove(query.First())
    End Sub
End Class

2 个答案:

答案 0 :(得分:3)

通常,基于推送的HTTP实现非常困难。用于实现此功能的Commom技术是反向Ajax Web套接字长轮询(有些甚至使用单个像素flex对象来保留套接字永久开放)。 看看这个Code Project Article,它使用Reverse Ajax aka Commet来实现一个能够推送通知的wcf休息服务。

答案 1 :(得分:0)

您需要将消息从Android设备发送到wcf服务,然后wcf服务会将消息转发给已注册的Windows客户端。