共用方式為


遠端處理範例:動態發行

本主題專門說明一項為了在現有應用程式中提供回溯相容性而保留的舊有技術,不建議用於新的開發工作。分散式應用程式應使用  Windows Communication Foundation (WCF) 進行開發。

.NET 遠端處理僅支援使用伺服器啟動之可遠端處理型別的預設建構函式。若要在使用特定建構函式來建立物件之後加以發行,並針對該特定執行個體的發行作業擁有完全的掌控權,您可以程式設計方式來發行執行個體。

1t63e8ff.Caution(zh-tw,VS.100).gif注意:
.NET 遠端處理依預設不進行驗證或加密。因此,建議您採取所有必要的步驟,以驗證用戶端或伺服器的識別,然後再與其進行遠端互動。由於 .NET 遠端應用程式需要 FullTrust 權限才能執行,所以如果某個未經授權的用戶端被授與伺服器的存取權,該用戶端就可以執行程式碼,如同它已完全受信任。請務必驗證您的端點並針對通訊資料流進行加密。如需詳細資訊,請參閱遠端處理中的安全性

若要編譯和執行這個範例

  1. 在命令提示字元上輸入下列命令:

    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
    
    csc -t:library remote.cs
    csc -r:System.Runtime.Remoting.dll -r:remote.dll server.cs
    csc -r:System.Runtime.Remoting.dll -r:remote.dll client.cs
    
  2. 開啟兩個指向相同目錄的命令提示字元。在其中一個提示字元底下,輸入 server。在另一個命令提示字元底下,輸入 client

  3. 若要停止在各階段中發行可遠端處理的物件,請在伺服器命令提示字元中按下 ENTER,並且重新執行用戶端,觀察針對不同階段擲回的不同例外狀況。這個應用程式會在單一電腦或網路上執行。若要透過網路執行這個應用程式,請將用戶端組態中的 "localhost" 取代為遠端電腦的名稱。

遠端

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
using System;
using System.Collections.Generic;
using System.Text;

namespace Remote
{
    public class ServiceClass : MarshalByRefObject
    {
        private DateTime m_startTime;

        public ServiceClass()
        {
            Console.WriteLine("ServiceClass created without constructor. Instance hash is " + GetHashCode().ToString());
            m_startTime = DateTime.Now;
        }

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

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

        public int InstanceHash
        {
            get { return GetHashCode(); }
        }
    }
}

伺服器

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

Module Module1

  Sub Main()
    Dim channel As New HttpChannel(8080)
    ChannelServices.RegisterChannel(channel, False)

    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 Module
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using Remote;

namespace Server
{
    class Server
    {
        static void Main(string[] args)
        {
            HttpChannel channel = new HttpChannel(8080);
            ChannelServices.RegisterChannel(channel, false);

            ServiceClass object1 = new ServiceClass();

            // Creates the single instance of ServiceClass. All clients
            // will use this instance.

            ObjRef ref1 = 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();
        }
    }
}

用戶端

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, False)

      ' 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     
End Class   
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using Remote;

namespace Client
{
    public class ClientProcess
    {
  [MTAThread]
        public static void Main(string[] args)
        {
            HttpChannel channel = new HttpChannel();
            ChannelServices.RegisterChannel(channel, false);

            // Registers the remote class. (This could be done with a
            // configuration file instead of a direct call.)
            RemotingConfiguration.RegisterWellKnownClientType(
                Type.GetType("Remote.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.
            ServiceClass object1 = new ServiceClass();

            try
            {
                Console.WriteLine("ServerTime: " + object1.GetServerTime());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception of type: " + ex.ToString() + " occurred.");
                Console.WriteLine("Details: " + ex.Message);
            }
        }
    }
}

另請參閱

參考

RemotingServices.Marshal Method
RemotingServices.Disconnect Method
ChannelServices.UnregisterChannel Method

其他資源

遠端處理範例