.NET Remoting HelloWorld

时间:2009-09-10 13:51:56

标签: .net remoting

这是我的Hello World Remoting App。

using System;
using System.Collections.Generic;
using System.Text;

namespace Remoting__HelloWorld.UI.Client
{
    public interface MyInterface
    {
        int FunctionOne(string str);
    }
}

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

namespace Remoting__HelloWorld.UI.Client
{
    class MyClient
    {
        public static void Main()
        {
            TcpChannel tcpChannel = new TcpChannel();

            ChannelServices.RegisterChannel(tcpChannel);

            MyInterface remoteObj = (MyInterface) 
            Activator.GetObject(typeof(MyInterface), "tcp://localhost:8080/FirstRemote");

            Console.WriteLine(remoteObj.FunctionOne("Hello World!"));
        }
    }
}


using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using Remoting__HelloWorld.UI.Client;

namespace Remoting__HelloWorld.UI.Server
{
    public class MyRemoteClass : MarshalByRefObject, MyInterface
    {
        public int FunctionOne(string str)
        {
            return str.Length;
        }
    }
}


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

namespace Remoting__HelloWorld.UI.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpChannel tcpChannel = new TcpChannel(9999);

            ChannelServices.RegisterChannel(tcpChannel);

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyRemoteClass), "FirstRemote", WellKnownObjectMode.SingleCall);

            System.Console.WriteLine("Press ENTER to quit");
            System.Console.ReadLine();
        }
    }
}

但在运行此应用程序后,我收到以下异常:

No connection could be made because the target machine 
actively refused it 127.0.0.1:8080

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

服务器tcpChannel是9999客户端请求8080

答案 1 :(得分:3)

当客户端正在寻找8080时,您的服务器正在端口9999上打开通道。

答案 2 :(得分:2)

像这样更改服务器:

TcpChannel tcpChannel = new TcpChannel(8080);

或像这样更改客户端:

Activator.GetObject(typeof(MyInterface), "tcp://localhost:9999/FirstRemote");

在服务器端,您在指定的端口号上打开一个通道(在您的示例中,您使用的是端口9999)。实质上,这告诉服务器“侦听”端口9999上的传入请求。在客户端,您告诉它要连接到哪个端口号(在您的示例中,您使用的是端口8080)。因此,您的服务器正在侦听端口9999,但您的客户端正尝试在端口8080上进行连接。这些端口号必须匹配。