110,545
社区成员
发帖
与我相关
我的任务
分享
//测试用的类
[Serializable]
public class c1
{ //获取本机时间
public string gettime()
{
return DateTime.Now.ToString();
}
}
//远程对象类
public class testRemoteServer : MarshalByRefObject
{
public string gettime()
{ //返回系统时间
return DateTime.Now.ToString();
}
public c1 TestC = new c1();
}
testRemoteServer tr= (testRemoteServer )System.Activator.GetObject(typeof(testRemoteServer ), "tcp://192.168.001.031:4001/testRemoteServer ");
MessageBox.Show("MarshalByRefObject的成员getTime返回:" +tr.gettime ()+"\r\nMarshalByRefObject的成员c1的方法gettime返回:" + tr.TestC.gettime ());
public class c1 : MarshalByRefObject //<--
{ //获取本机时间
public string gettime()
{
return DateTime.Now.ToString();
}
public string Test()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
void Test()
{
AppDomain domain = AppDomain.CreateDomain("hello new domain");
testRemoteServer proxy = (testRemoteServer)domain.CreateInstanceAndUnwrap(typeof(testRemoteServer).Assembly.FullName, typeof(testRemoteServer).FullName);
string s = proxy.TestC.gettime(); // <-- "hello new domain"
}
另外,如果c1不能继承自MarshalByRefObject,你也可以在testRemoteServer中添加一个方法,在该方法中调用return this.TestC.gettime();
[ServiceContract]
public interface IHello
{
[OperationContract]
string gettime();
[OperationContract]
c1 testc();
}
public class HelloWorld : IHello
{
public string gettime()
{
return DateTime.Now.ToString();
}
public c1 testc()
{
return new c1();
}
}
public class c1
{
public string gettime()
{
return DateTime.Now.ToString();
}
}
客户端代码
[ServiceContract]
public interface IHello
{
[OperationContract]
string gettime();
[OperationContract]
c1 testc();
}
public class c1
{
public string gettime()
{
return "本地";
}
}
void main()
{
ServiceEndpoint httpEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(IHello))
, new BasicHttpBinding(), new EndpointAddress(@"http://localhost:4002/HelloService/Svc"));
using (ChannelFactory<IHello> factory = new ChannelFactory<IHello>(httpEndpoint))
{
IHello service = factory.CreateChannel();
MessageBox.Show(service.gettime());
MessageBox.Show(service.testc().gettime());
}