C# - Самый простой пример Remoting приложения

Несмотря на то, что некоторые считают, что Remoting устарел, я все равно остаюсь его поклонником, для тех кому просто нужно, чтобы все работало без заморочек это отличный пример.
Тут всего 3 класса, которые можно разместить в 1 библиотеке и подключить ее к приложению сервера и клиента.
Создание сервера происходит в 1 строку:
Remote.Server Server = new Remote.Server();
При этом можно спокойно разместить ее например в классе формы и не бояться, что все повиснет.

Обращение к серверу проходит в 2 строки:
Remote.Client client = new Remote.Client(); //подключение к серверу, можно задать IP и порт
client.remoteObject.GetRemoteStatus("test");//Выполнение запроса к серверу, где GetRemoteStatus имя удаленной функции.
Скачать исходник целиком можно по ссылке.
Клиент:
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace Remote
{
   public class Client
    {
        public SharedTypeInterface remoteObject;
        public Client(string host = "localhost",int port =9998)
        {
            TcpChannel tcpChannel = new TcpChannel();
            bool needreg = true;
            foreach (var item in ChannelServices.RegisteredChannels )
            {
                if (item.ChannelName==tcpChannel.ChannelName )
                {
                    needreg = false;
                }
            }
            if (needreg )
            {
                ChannelServices.RegisterChannel(tcpChannel);
            }
            

            Type requiredType = typeof(SharedTypeInterface);

            remoteObject = (SharedTypeInterface)Activator.GetObject(requiredType,
            "tcp://"+ host+":"+port.ToString()+"/RemoteService");
            Console.WriteLine(remoteObject.GetRemoteStatus("Ticket No: 3344"));
        }
    }
}

Сервер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading.Tasks;

namespace Remote
{
    public class Server
    {
        public Server(int port=9998)
        {
            Console.WriteLine("Remote Server started...");

            TcpChannel tcpChannel = new TcpChannel(port);
            ChannelServices.RegisterChannel(tcpChannel);

            Type commonInterfaceType = Type.GetType("Remote.SharedType");

            RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
            "RemoteService", WellKnownObjectMode.SingleCall);

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

    
}

Общий класс:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Remote
{
    public interface SharedTypeInterface
    {
        string GetRemoteStatus(string stringToPrint);
    }

    public class SharedType : MarshalByRefObject, SharedTypeInterface
    {
        public string GetRemoteStatus(string stringToPrint)
        {
            string returnStatus = "Ticket Confirmed";
            Console.WriteLine("Enquiry for {0}", stringToPrint);
            Console.WriteLine("Sending back status: {0}", returnStatus);

            return returnStatus;
        }
    }
}

Комментарии

Популярные сообщения