Partager via


Exemple d'accès distant : Publication dynamique

.NET Remoting prend en charge uniquement des constructeurs par défaut dont les types accessibles à distance sont activés par le serveur. Si vous voulez publier un objet après l'avoir créé à l'aide de constructeurs spécifiques et avoir un contrôle total de la publication de cette instance spécifique, vous pouvez publier votre instance par programme.

ATTENTION   .NET Remoting n'effectue aucune authentification ni aucun cryptage par défaut. Par conséquent, il est recommandé d'effectuer toutes les opérations nécessaires pour vous assurer de l'identité des clients ou des serveurs avant d'interagir avec eux à distance. Étant donné que les applications .NET Remoting exigent les autorisations FullTrust pour s'exécuter, si un client non autorisé se voyait accorder l'accès à votre serveur, il pourrait exécuter du code comme s'il était d'un niveau de confiance suffisant. Authentifiez toujours vos points d'entrée et cryptez les flux de communication, en hébergeant vos types distants dans IIS (Internet Information Services) ou en créant une paire de récepteurs de canal personnalisée pour effectuer cette tâche.

Pour compiler et exécuter cet exemple

  1. Tapez les commandes suivantes à l'invite de commande :

    vbc -t:library remote.vb

    vbc -r:System.Runtime.Remoting.dll -r:remote.dll server.vb

    vbc -r:System.Runtime.Remoting.dll -r:remote.dll client.vb

  2. Ouvrez deux invites de commande pointant vers le même répertoire. Dans la première, tapez server. Dans l'autre, tapez client.

Pour arrêter la publication de l'objet accessible à distance par étapes, appuyez sur la touche ENTRÉE dans l'invite de commande de serveur et exécutez de nouveau le client pour observer les différentes exceptions levées lors des différentes étapes. Cette application s'exécute sur un ordinateur unique ou sur un réseau. Si vous voulez exécuter cette application sur un réseau, vous devez remplacer « localhost » dans la configuration du client par le nom de l'ordinateur distant.

remote.vb

Imports System

Public Class ServiceClass
   Inherits MarshalByRefObject

   Private m_starttime As DateTime

   Public Sub New()
      Console.WriteLine("ServiceClass created without constructor. Instance hash is " & Me.GetHashCode().ToString())
      m_starttime = DateTime.Now
   End Sub   

   Overrides Protected Sub Finalize()
      Console.WriteLine("I'm being collected after " & (New TimeSpan(DateTime.Now.Ticks - m_starttime.Ticks)).ToString() & " seconds.")
      MyBase.Finalize()
   End Sub    

   Public Function GetServerTime() As DateTime
      Console.WriteLine("Time requested by a client.")
      Return DateTime.Now
   End Function   

   Public ReadOnly Property InstanceHash() As Integer
      Get
         Return Me.GetHashCode()
      End Get
   End Property 

End Class

Server.vb

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http

Public Class ServerProcess
   <MTAThread()> _
   Public Shared Sub Main()

      Dim channel As New HttpChannel(8080)
      ChannelServices.RegisterChannel(channel)

      Dim object1 As New ServiceClass()

      ' Creates the single instance of ServiceClass. All clients
      ' will use this instance.
      Dim ref1 As ObjRef = RemotingServices.Marshal(object1, "object1uri")
      Console.WriteLine("ObjRef.URI: " & ref1.URI)

      Console.WriteLine("Running. Press Enter to end publication.")
      Console.ReadLine()

      ' This unregisters the object from publication, but leaves
      ' the channel listening.
      RemotingServices.Disconnect(object1)
      Console.WriteLine()
      Console.WriteLine("Disconnected the object. Client now receives a RemotingException.")
      Console.WriteLine("Press Enter to unregister the channel.")
      Console.ReadLine()
      ' At this point, the ServerClass object still exists. The server
      ' could republish it.

      ' This unregisters the channel, but leaves the application 
      ' domain running.
      ChannelServices.UnregisterChannel(channel)
      Console.WriteLine("Unregistered the channel. Client now receives a WebException.")
      ' The ServerClass object still exists. The server could
      ' reregister the channel and republish the object.
      Console.WriteLine("The host application domain is still running. Press Enter to stop the process.")
      Console.ReadLine()

      ' The ServiceClass object's Finalize method writes a message to
      ' the console. A single object will almost always succeed in 
      ' running its Finalize method before the Console is finalized;
      ' in a larger application, you could ensure that all objects 
      ' finalize before the application ends by calling the garbage 
      ' collector and waiting.
      GC.Collect()
      GC.WaitForPendingFinalizers()
   End Sub
   
End Class

Client.vb

Imports System 
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Channels.Http

Public Class ClientProcess
   <MTAThread()> _
   Public Shared Sub Main()
      
      Dim channel As New HttpChannel(0)
      ChannelServices.RegisterChannel(channel)

      ' Registers the remote class. (This could be done with a
      ' configuration file instead of a direct call.)
      RemotingConfiguration.RegisterWellKnownClientType(Type.GetType("ServiceClass, remote"), "https://localhost:8080/object1uri")

      ' Instead of creating a new object, this obtains a reference
      ' to the server's single instance of the ServiceClass object.
      Dim object1 As ServiceClass = New ServiceClass()

      Try
         Console.WriteLine("ServerTime: " & object1.GetServerTime())
      Catch ex As Exception
         Console.WriteLine("Exception of type: " & ex.GetType.ToString & " occurred.")
         Console.WriteLine("Details: " & ex.Message)
      End Try

   End Sub     ' Main
End Class   ' ClientProcess

Voir aussi

Exemples d'accès distant | RemotingServices.Marshal, méthode | RemotingServices.Disconnect, méthode | ChannelServices.UnregisterChannel, méthode