الاتصال عن بعد .NET HelloWorld
سؤال
وهذا هو بلدي مرحبا العالم الاتصال عن بعد التطبيق.
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
وكيف يمكن إصلاح هذا؟
المحلول
وإما تغيير الخادم مثل هذا:
TcpChannel tcpChannel = new TcpChannel(8080);
وأو تغيير العميل مثل هذا:
Activator.GetObject(typeof(MyInterface), "tcp://localhost:9999/FirstRemote");
وعلى جانب الملقم، وكنت فتح قناة على رقم المنفذ المحدد (في المثال الخاص بك، وأنت باستخدام منفذ 9999). في جوهرها، وهذا يقول الخادم إلى "الاستماع" للطلبات الواردة على المنفذ 9999. على جانب العميل، وكنت اقول انه ما رقم المنفذ للاتصال (في المثال الخاص بك، كنت تستخدم المنفذ 8080). بحيث يكون لديك الحالة التي تكون فيها الخادم الخاص بك هو الاستماع على المنفذ 9999، ولكن العميل يحاول الاتصال على المنفذ يجب 8080. هذه الأرقام ميناء المباراة.
نصائح أخرى
وخادم tcpChannel هو 9999 طلبات العميل نحو 8080
والخادم الخاص بك هو فتح قناة على المنفذ 9999 بينما تتطلع العميل عن 8080.