What steps do I need to take to use WCF Callbacks?

后端 未结 4 748
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 06:46

I am trying to learn WCF. I have a simple client and server application setup and upon pressing a button on the client, it gets an updated value from the server.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 07:27

    I know, old question... I came across this question from a google search earlier today and the answer provided by Ray Vernagus is the easiest to understand example of WCF that I have read to date. So much so that I was able to rewrite it in VB.NET without using any online converters. I thought I'd add the VB.NET variant of the example that Ray Vernagus provided. Just create a new VB.NET Windows Console application, add a reference to System.ServiceModel, and copy/paste the entire code below into the default Module1 class file.

    Imports System.ServiceModel
    Imports System.ServiceModel.Channels
    
    
    
    Public Interface IMyContractCallback
         _
        Sub OnCallBack()
    End Interface
    
     _
    Public Interface IMyContract
         _
        Sub DoSomething()
    End Interface
    
     _
    Public Class Myservice
        Implements IMyContract
    
        Public Sub DoSomething() Implements IMyContract.DoSomething
            Console.WriteLine("Hi from server!")
            Dim callback As IMyContractCallback = OperationContext.Current.GetCallbackChannel(Of IMyContractCallback)()
            callback.OnCallBack()
        End Sub
    End Class
    
    Public Class MyContractClient
        Inherits DuplexClientBase(Of IMyContract)
    
        Public Sub New(ByVal callbackinstance As Object, ByVal binding As Binding, ByVal remoteAddress As EndpointAddress)
            MyBase.New(callbackinstance, binding, remoteAddress)
        End Sub
    End Class
    
    Public Class MyCallbackClient
        Implements IMyContractCallback
    
        Public Sub OnCallBack() Implements IMyContractCallback.OnCallBack
            Console.WriteLine("Hi from client!")
        End Sub
    End Class
    
    
    Module Module1
    
        Sub Main()
            Dim uri As New Uri("net.tcp://localhost")
            Dim binding As New NetTcpBinding()
            Dim host As New ServiceHost(GetType(Myservice), uri)
            host.AddServiceEndpoint(GetType(IMyContract), binding, "")
            host.Open()
    
            Dim callback As New MyCallbackClient()
            Dim client As New MyContractClient(callback, binding, New EndpointAddress(uri))
            Dim proxy As IMyContract = client.ChannelFactory.CreateChannel()
    
            proxy.DoSomething()
            ' Printed in console:
            '  Hi from server!
            '  Hi from client!
    
            Console.ReadLine()
    
            client.Close()
            host.Close()
        End Sub
    
    End Module
    

提交回复
热议问题