Tải bản đầy đủ (.pdf) (59 trang)

Programming C# 2nd Edition phần 9 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (682.7 KB, 59 trang )

Programming C#, 2nd Edition
467
In this case the server is assumed to be running on your local machine, so the URI is
http://localhost, followed by the port for the server (65100), followed in turn by the endpoint
you declared in the server (theEndPoint).
The remoting service should return an object representing the interface you've requested. You
can then cast that object to the interface and begin using it. Because remoting cannot be
guaranteed (the network might be down, the host machine may not be available, and so forth),
you should wrap the usage in a try block:
try
{
Programming_CSharp.ICalc calc =
obj as Programming_CSharp.ICalc;

double sum = calc.Add(3,4);
You now have a proxy of the Calculator operating on the server, but usable on the client,
across the process boundary and, if you like, across the machine boundary. Example 19-4
shows the entire client (to compile it, you must include a reference to ICalc.dll as you did
with CalcServer.cs).
Example 19-4. The remoting Calculator client
namespace Programming_CSharp
{
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

public class CalcClient
{
public static void Main( )
{



int[] myIntArray = new int[3];

Console.WriteLine("Watson, come here I need you ");

// create an Http channel and register it
// uses port 0 to indicate won't be listening
HttpChannel chan = new HttpChannel(0);
ChannelServices.RegisterChannel(chan);

// get my object from across the http channel
MarshalByRefObject obj =
(MarshalByRefObject) RemotingServices.Connect
(typeof(Programming_CSharp.ICalc),
"http://localhost:65100/theEndPoint");

try
{
// cast the object to our interface
Programming_CSharp.ICalc calc =
obj as Programming_CSharp.ICalc;



×