Esempio di comunicazione remota: servizio di rilevamento

La classe TrackingServices fornisce un servizio di rilevamento generale con gestori di rilevamento innestabili. I metodi dell'interfaccia ITrackingHandler vengono chiamati nelle circostanze descritte di seguito.

  • È stato generato un oggetto ObjRef come risultato di un marshalling.
  • È stato ricevuto un ObjRef come risultato di un unmarshalling.
  • È stato disconnesso un oggetto.

Per ulteriori informazioni, vedere TrackingServices e ITrackingHandler nella documentazione di riferimento.

Attenzione   .NET Remoting non consente di effettuare l'autenticazione né la crittografia per impostazione predefinita. Si consiglia dunque di eseguire tutte le azioni necessarie per verificare l'identità dei client o dei server prima di interagire con essi in modalità remota. Poiché l'esecuzione delle applicazioni .NET Remoting richiede autorizzazioni FullTrust, qualora a un client non autorizzato venisse concesso l'accesso al server, il client potrebbe eseguire codice come se fosse completamente attendibile. È necessario autenticare sempre gli endpoint e crittografare i flussi di comunicazione mediante l'hosting dei tipi remoti in Internet Information Services (IIS) oppure generando a questo scopo una coppia di sink di canale personalizzata.

Per compilare ed eseguire l'esempio

  1. Digitare i seguenti comandi al prompt dei comandi:

    [C#]

    csc /t:library TrackingHandler.cs

    csc /r:System.Runtime.Remoting.dll /t:library /out:ServiceClass.dll serviceclass.cs

    csc /r:System.Runtime.Remoting.dll /r:ServiceClass.dll client.cs

    csc /r:System.Runtime.Remoting.dll /r:TrackingHandler.dll /r:ServiceClass.dll server.cs

  2. Aprire due prompt dei comandi che puntino alla stessa directory. In uno, digitare server e nell'altro client.

Questa applicazione viene eseguita su un singolo computer o in una rete. Per eseguire l'applicazione in una rete, nella configurazione del client è necessario sostituire hostlocale con il nome del computer remoto.

TrackingHandler.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Services;

public class TrackingHandler : ITrackingHandler{

   // Notifies a handler that an object has been marshaled.
   public void MarshaledObject(Object obj, ObjRef or){
      Console.WriteLine("Tracking: An instance of {0} was marshaled. The instance HashCode is: {1}", obj.ToString(), obj.GetHashCode().ToString());
      Console.WriteLine("ObjRef dump:");
      if (or.ChannelInfo != null){
         Console.WriteLine("  -- ChannelInfo: ");
         DumpChannelInfo(or.ChannelInfo);
      }
      if (or.EnvoyInfo != null)
         Console.WriteLine("  -- EnvoyInfo: " + or.EnvoyInfo.ToString());
      if (or.TypeInfo != null){
         Console.WriteLine("  -- TypeInfo: " + or.TypeInfo.ToString());
         Console.WriteLine("      -- " + or.TypeInfo.TypeName);
      }
      if (or.URI != null)
         Console.WriteLine("  -- URI: " + or.URI.ToString());
   }

   private void DumpChannelInfo(IChannelInfo info){

      foreach(object obj in info.ChannelData){
         if(obj is ChannelDataStore){
            foreach(string uri in ((ChannelDataStore)obj).ChannelUris)
               Console.WriteLine("      -- ChannelUris:" + uri);
         }
      }
   }

   // Notifies a handler that an object has been unmarshaled.
   public void UnmarshaledObject(Object obj, ObjRef or){
   Console.WriteLine("Tracking: An instance of {0} was unmarshaled. The instance HashCode is: {1}", obj.ToString(), obj.GetHashCode().ToString());
   }

   // Notifies a handler that an object has been disconnected.
   public void DisconnectedObject(Object obj){
   Console.WriteLine("Tracking: An instance of {0} was disconnected. The instance HashCode is: {1}", obj.ToString(), obj.GetHashCode().ToString());
   }
}

Server.cs

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Services;

public class ServerProcess{

   public static void Main(string[] Args){

      TcpChannel channel = new TcpChannel(8080);
      ChannelServices.RegisterChannel(channel);

      TrackingServices.RegisterTrackingHandler(new TrackingHandler());

      ServiceClass service  = new ServiceClass();
      ObjRef obj = RemotingServices.Marshal(service,"TcpService");

      Console.WriteLine("\r\nPress Enter to unmarshal the object.");
      Console.ReadLine();

      RemotingServices.Unmarshal(obj);

      Console.WriteLine("Press Enter to disconnect the object.");
      Console.ReadLine();

      RemotingServices.Disconnect(service);
   }
}

Client.cs

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

public class ClientProcess{

   public static void Main(string[] Args){

      ChannelServices.RegisterChannel(new TcpChannel());

      WellKnownClientTypeEntry remotetype = new WellKnownClientTypeEntry(typeof(ServiceClass),"tcp://localhost:8080/TcpService");
      RemotingConfiguration.RegisterWellKnownClientType(remotetype);

      ServiceClass service = new ServiceClass(); 
      Console.WriteLine("Server time is: " + service.GetServerTime().ToLongTimeString());

   }
}

ServiceClass.cs

using System;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;

public class ServiceClass : MarshalByRefObject{

   private DateTime starttime;

   public ServiceClass(){
      Console.WriteLine("A ServiceClass has been created.");
      starttime = DateTime.Now;
   }

   ~ServiceClass(){
      Console.WriteLine("ServiceClass being collected after " + (new TimeSpan(DateTime.Now.Ticks - starttime.Ticks)).ToString() + " seconds.");
    
   }

   public DateTime GetServerTime(){
      Console.WriteLine("Time requested by client.");
      return DateTime.Now;
   }
}

Vedere anche

Esempi di comunicazione remota | ITrackingHandler | TrackingServices