processmessage.cs

来自「一个进程间通信列子」· CS 代码 · 共 87 行

CS
87
字号
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Collections;

namespace AIO
{
    public enum ProcessName
    {
        PZPT = 8880,
        ZSK = 8881,
        QBJS = 8882,
        LCKZ = 8885

     
    }

    public class Process
    {
        private Hashtable _processes = Hashtable.Synchronized(new Hashtable());
        protected ProcessName _name;

        public ProcessName Name
        {
            get { return _name; }
        }

        public Process(ProcessName name)
        {
            _name = name;
            AddProcessProxy(ProcessName.PZPT);
            AddProcessProxy(ProcessName.ZSK);
            AddProcessProxy(ProcessName.QBJS);
            AddProcessProxy(ProcessName.LCKZ);
        }

        private void AddProcessProxy(ProcessName procName)
        {
            int port = (int)procName;
            _processes.Add(procName, string.Format("tcp://localhost:{0}/Proxy", port));
        }

        public virtual string OnRecieveMessage(string message, string param, ProcessName fromProcess)
        {
            return "";
        }

        public string SendMessage(string message, string param, ProcessName toProcess)
        {
            string ppxyAddress = _processes[toProcess] as string;
            if (ppxyAddress == null)
                return null;
            ProcessProxy ppxy = (ProcessProxy)Activator.GetObject(typeof(ProcessProxy), ppxyAddress);
            return ppxy.OnRecieveMessage(message, param, _name);
        }
    }

    public class ProcessProxy
        :MarshalByRefObject
    {
        private static Process _process;

        public static void InitOnServer(Process proc)
        {
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            Dictionary<string, string> properties = new Dictionary<string, string>();
            properties["name"] = "Client"; 
            TcpClientChannel clientChannel = new TcpClientChannel(properties,clientProvider);
            ChannelServices.RegisterChannel(clientChannel, false);
            int port = (int)(proc.Name);
            TcpServerChannel channel = new TcpServerChannel("TcpChannel",port);
     
            ChannelServices.RegisterChannel(channel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcessProxy), "Proxy", WellKnownObjectMode.SingleCall);
            _process = proc;
        }

        public string OnRecieveMessage(string message, string param, ProcessName fromProcess)
        {
            return _process.OnRecieveMessage(message,param,fromProcess);
        }
    }    
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?