Наследование: RpcMessageDispatcher.Client
Пример #1
0
        public void dispatchMsg(RpcMessage m)
        {
            RpcServantDelegate dg = null;

            if ((m.calltype & RpcMessage.CALL) != 0)
            {
                lock (_servants) {
                    if (!_servants.ContainsKey(m.ifidx))
                    {
                        doError(RpcException.RPCERROR_INTERFACE_NOTFOUND, m);
                        return;
                    }
                    dg = _servants[m.ifidx];
                }
                try {
                    RpcMessage msgreturn = dg.invoke(m);
                    if (msgreturn != null)
                    {
                        m.conn.sendMessage(msgreturn);
                    }
                }
                catch (Exception e) {
                    RpcCommunicator.instance().logger.error(" execute servant failed:" + e.ToString());
                    doError(RpcException.RPCERROR_REMOTEMETHOD_EXCEPTION, m);
                }
            }
        }
Пример #2
0
 public static RpcCommunicator instance()
 {
     if (RpcCommunicator._handle == null) {
         RpcCommunicator._handle = new RpcCommunicator();
     }
     return RpcCommunicator._handle;
 }
Пример #3
0
        protected override bool sendDetail(RpcMessage m)
        {
            if (!isConnected)
            {
                if (!connect())
                {
                    return(false);
                }
            }
            if (_sent_num == 0)   //第一次连接进入之后的第一个数据包需要携带令牌和设备标识码,用于接入服务器的验证
            {
                if (_token != null && !_token.Equals(""))
                {
                    m.extra.setPropertyValue("__token__", _token);
                    m.extra.setPropertyValue("__device_id__", RpcCommunicator.getSystemDeviceID());
                }
            }

            //byte[] body = null;
            //body = ((MemoryStream) m.marshall()).ToArray();
            byte[] bytes = createMsgBody(m).ToArray();
            _sock.Send(bytes);
            _sent_num++;
            return(true);
        }
Пример #4
0
        //从二进制流中反序列化出对象RpcMessage
        public static RpcMessage unmarshall(Stream stream)
        {
            RpcMessage   m      = new RpcMessage();
            BinaryReader reader = new BinaryReader(stream);

            try {
                m.type      = RpcBinarySerializer.readByte(reader);
                m.sequence  = RpcBinarySerializer.readInt(reader);
                m.calltype  = RpcBinarySerializer.readByte(reader);
                m.ifidx     = RpcBinarySerializer.readShort(reader);
                m.opidx     = RpcBinarySerializer.readShort(reader);
                m.errcode   = RpcBinarySerializer.readInt(reader);
                m.paramsize = RpcBinarySerializer.readByte(reader);
                m.call_id   = RpcBinarySerializer.readShort(reader);
                if (m.extra.unmarshall(stream) == false)
                {
                    return(null);
                }
                m.paramstream = reader.ReadBytes((int)(stream.Length - stream.Position));
            }
            catch (Exception e) {
                RpcCommunicator.instance().logger.error(e.ToString());
                m = null;
            }
            return(m);
        }
Пример #5
0
        protected bool sendBufferredMsg()
        {
            if (_unsent_msglist.Count == 0)
            {
                return(true);
            }
            RpcMessage m = _unsent_msglist[0];

            _unsent_msglist.RemoveAt(0);

            if (_sent_num == 0)
            { //第一次连接进入之后的第一个数据包需要携带令牌和设备标识码,用于接入服务器的验证
                if (_token != null && !_token.Equals(""))
                {
                    m.extra.setPropertyValue("__token__", _token);
                    m.extra.setPropertyValue("__device_id__", RpcCommunicator.getSystemDeviceID());
                }
            }

            byte[] bytes = createMsgBody(m).ToArray();

            _sock.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, delegate(IAsyncResult ar) {
                try {
                    RpcConnectionAsyncSocket s = (RpcConnectionAsyncSocket)ar.AsyncState;
                    s.sendBufferredMsg();
                }
                catch (Exception e) {
                    RpcCommunicator.instance().logger.error("BeginSend failed:" + e.ToString());
                }
            }, this);

            _sent_num++;
            return(true);
        }
Пример #6
0
        /**
         * 打开本地通信端点,用于接收远程客户连接到达
         *  (server end)
         */
        //public RpcConnection openEndpoint(RpcEndpoint ep) {

        //    return null;
        //}

        public bool open()
        {
            bool succ = false;

            if (_settings.threadNum > 0)
            {
                _dispatcher = new RpcMessageDispatcher(this, _settings.threadNum);
                succ        = _dispatcher.open();
            }

            // if acceptor has not opened, then do open.
            lock (_acceptors) {
                foreach (RpcConnectionAcceptor acceptor in _acceptors)
                {
                    if (acceptor.isOpen == false)
                    {
                        if (!acceptor.open())
                        {
                            RpcCommunicator.instance()
                            .logger.error("open connection acctor failed! " + acceptor.ToString());
                        }
                    }
                }
            }
            return(succ);
        }
Пример #7
0
 public static RpcCommunicator instance()
 {
     if (RpcCommunicator._handle == null)
     {
         RpcCommunicator._handle = new RpcCommunicator();
     }
     return(RpcCommunicator._handle);
 }
Пример #8
0
 public RpcMessage(int calltype = UNDEFINED)
 {
     this.calltype = calltype;
     if ((calltype & CALL) != 0)
     {
         sequence = RpcCommunicator.instance().getUniqueSequence();
     }
 }
Пример #9
0
        protected override void run()
        {
            //接收数据
            long recv_num = 0;

            byte[]       bytes  = new byte[1024];
            MemoryStream stream = new MemoryStream();

            RpcCommunicator.instance().logger.debug("thread of connection come in..");
            try {
                this.onConnected();
                while (true)
                {
                    int size = _sock.Receive(bytes);
                    if (size > 0)
                    {
                        stream.Seek(0, SeekOrigin.End);
                        stream.Write(bytes, 0, size);
                    }
                    else
                    {
                        break;
                    }
                    List <MemoryStream> streamlist = new List <MemoryStream>();
                    stream.Seek(0, SeekOrigin.Begin);
                    ReturnValue rv = parsePacket(stream);
                    if (rv.code == ReturnValue.DATA_DIRTY)
                    {
                        this.close(); // destroy the socket , connection be lost.
                        RpcCommunicator.instance().logger.debug("data dirty, break out");
                        break;
                    }

                    BinaryReader reader  = new BinaryReader(stream);
                    byte[]       remains = reader.ReadBytes((int)(stream.Length - stream.Position));
                    stream = new MemoryStream();
                    stream.Write(remains, 0, remains.Length);
                    // left bytes be picked out .
                    foreach (RpcMessage m in rv.msglist)
                    {
                        this.onMessage(m);
                    }
                }
            }
            catch (Exception e) {
                RpcCommunicator.instance().logger.debug(e.ToString());
            }

            onDisconnected();
            RpcCommunicator.instance().logger.debug("thread of connection leaving..");
        }
Пример #10
0
        protected virtual void doReturnMsg(RpcMessage m2)
        {
            RpcMessage m1 = null;

            // count+=1;

            m1 = RpcCommunicator.instance().dequeueMessage(m2.sequence);

            if (m1 != null)
            {
                if (m1.async != null)
                {
                    // it will raise exception in user callback function
                    try {
                        if (m2.errcode != RpcException.RPCERROR_SUCC)
                        {
                            // remote exception
                            //m1.async.ctx.exception = new RpcException(m2.errcode);
                            if (m1.async.promise != null)
                            {
                                RpcAsyncContext ctx = new RpcAsyncContext();
                                ctx.promise   = m1.async.promise;
                                ctx.exception = new RpcException(m2.errcode);
                                m1.async.promise.onError(ctx);
                            }
                            else
                            {
                                m1.async.onError(m2.errcode);
                            }
                        }
                        else
                        {
                            m1.async.callReturn(m1, m2);
                        }
                    }
                    catch (Exception e) {
                        RpcCommunicator.instance().logger.error("User CallBack failed: m1.async.callReturn ." + e.ToString());
                    }
                }
                else
                {
                    lock (m1){
                        m1.result = m2;                     // assing to init-caller
                        //m1.notify();
                        m1.ev.Set();
                    }
                }
            }
        }
Пример #11
0
 protected virtual void onMessage(RpcMessage m)
 {
     if (_adapter == null && _acceptor != null && _acceptor.adapter != null) // the connection from acceptor
     {
         _adapter = _acceptor.adapter;
     }
     if (_adapter != null && _adapter.dispatcher != null)  //由adapter的线程执行
     {
         _adapter.dispatcher.dispatchMsg(m);
     }
     else   //由全局通信器进行调度执行
     {
         RpcCommunicator.instance().dispatchMsg(m);
     }
 }
Пример #12
0
        private void dataRecieve(IAsyncResult ar)
        {
            try {
                int recv_size = _sock.EndReceive(ar);
                if (recv_size > 0)
                {
                    _stream.Seek(0, SeekOrigin.End);
                    _stream.Write(_bytes, 0, recv_size);

                    List <MemoryStream> streamlist = new List <MemoryStream>();
                    _stream.Seek(0, SeekOrigin.Begin);
                    ReturnValue rv = parsePacket(_stream);
                    if (rv.code == ReturnValue.DATA_DIRTY)
                    {
                        this.close(); // destroy the socket , connection be lost.
                        RpcCommunicator.instance().logger.debug("data dirty, break out");
                        onDisconnected();
                        return;
                    }

                    BinaryReader reader  = new BinaryReader(_stream);
                    byte[]       remains = reader.ReadBytes((int)(_stream.Length - _stream.Position));
                    _stream = new MemoryStream();
                    _stream.Write(remains, 0, remains.Length);
                    // left bytes be picked out .
                    foreach (RpcMessage m in rv.msglist)
                    {
                        this.onMessage(m);
                    }
                    _sock.BeginReceive(_bytes, 0, _bytes.Length, SocketFlags.None, dataRecieve, this);
                }
                else
                {
                    // socket lost
                    onDisconnected();
                }
            }
            catch (Exception e) {
                RpcCommunicator.instance().logger.debug("socket connection lost:" + e.ToString());
                onDisconnected();
            }
        }
Пример #13
0
 /**
  * 处理线程一次取走当前队列中所有消息,并批处理执行
  */
 private void threadMessageProcess()
 {
     while (_running)
     {
         _read_ev.WaitOne();
         List <RpcMessage> msglist;
         lock (_messages)
         {
             msglist   = _messages;
             _messages = new List <RpcMessage>();
         }
         if (msglist != null)
         {
             foreach (RpcMessage message in msglist)
             {
                 message.conn.dispatchMsg(message);  //分派到connection对象处理
             }
         }
     }
     RpcCommunicator.instance().logger.debug(string.Format("thread  of dispatcher({0}) exiting .. ", _client.getName()));
 }
Пример #14
0
        public virtual bool sendMessage(RpcMessage m)
        {
            if ((m.calltype & RpcMessage.CALL) != 0 && (m.calltype & RpcMessage.ONEWAY) == 0)
            {
                m.conn = this;
                //请求 Communicator 进行调度
                RpcCommunicator.instance().enqueueMessage(m.sequence, m);
            }
            bool r = false;

            lock (this) {
                r = sendDetail(m);
            }
            if (!r)  //发送失败,清除队列消息
            {
                if ((m.calltype & RpcMessage.CALL) != 0 && (m.calltype & RpcMessage.ONEWAY) == 0)
                {
                    RpcCommunicator.instance().dequeueMessage(m.sequence);
                }
            }
            return(r);
        }
Пример #15
0
        protected override bool connect()
        {
            IPAddress  addr = IPAddress.Parse(_ep.host);
            IPEndPoint ep   = new IPEndPoint(addr, _ep.port);

            _status = ConnectStatus.CONNECTING;
            _sock   = newSocket();
            _sock.BeginConnect(ep, delegate(IAsyncResult ar) {
                RpcConnectionAsyncSocket s = (RpcConnectionAsyncSocket)ar.AsyncState;
                try {
                    s.handler.EndConnect(ar);
                    if (s.handler.Connected == true)
                    {
                        s.onConnected();
                        //s._thread = new Thread(run);
                        //s._thread.Start();  // launch one thread for data recieving .
                    }
                }
                catch (Exception e) {
                    // connect failed
                    //s.onDisconnected();
                    RpcCommunicator.instance().logger.error("connect to host failed!");
                }
                //connect failed, trigger event to user as Promise
                if (s.handler.Connected == false)
                {
                    foreach (RpcMessage m in _unsent_msglist)
                    {
                        RpcAsyncContext ctx = m.async.ctx;
                        ctx.exception       = new RpcException(RpcException.RPCERROR_CONNECT_FAILED);
                        m.async.promise.onError(ctx);
                    }
                    _unsent_msglist.Clear();
                }
                s._status = ConnectStatus.STOPPED;
            }, this);

            return(true);
        }
Пример #16
0
        protected void _timerCheckHealth(object source, System.Timers.ElapsedEventArgs e)
        {
            //RpcCommunicator.instance().logger.debug("Communicator:: health checking..");
            List <RpcMessage> removeList = new List <RpcMessage>();

            lock (_cachedMsgList){
                long       cursec         = Utility.unixTimestamp(DateTime.Now);
                List <int> deprecatedlist = new List <int>();
                foreach (KeyValuePair <int, RpcMessage> kv in _cachedMsgList)
                {
                    if ((cursec - kv.Value.issuetime) * 1000 > _settings.callwait)
                    {
                        deprecatedlist.Add(kv.Key);
                    }
                }
                foreach (int seq in deprecatedlist)
                {
                    removeList.Add(_cachedMsgList[seq]);
                    _cachedMsgList.Remove(seq);
                    RpcCommunicator.instance().logger.error(String.Format("message({0}) be dropped for timeout", seq));
                }
            }
            //
            foreach (RpcMessage message in removeList)
            {
                if (message.async.promise == null)
                {
                    message.async.onError(RpcException.RPCERROR_TIMEOUT);
                }
                else
                {
                    RpcAsyncContext ctx = new RpcAsyncContext();
                    ctx.promise   = message.async.promise;
                    ctx.exception = new RpcException(RpcException.RPCERROR_TIMEOUT);
                    message.async.promise.onError(ctx);
                }
            }
        }
Пример #17
0
        //BinaryReader 以 Little-Endian 格式读取此数据类型。
        // Network Order is Big-Endian
        public bool unmarshall(Stream d)
        {
            try{
                BinaryReader reader = new BinaryReader(d);
                int          size   = 0;

                size = RpcBinarySerializer.readInt(reader);
                string key, val;
                //byte[] bytes;
                //int len = 0;

                for (int n = 0; n < size; n++)
                {
                    key = RpcBinarySerializer.readString(reader);
                    val = RpcBinarySerializer.readString(reader);
                    _props.Add(key, val);
                }
            }catch (Exception e) {
                RpcCommunicator.instance().getLogger().error(e.ToString());
                return(false);
            }
            return(true);
        }
Пример #18
0
        protected virtual void doReturnMsg(RpcMessage m2)
        {
            RpcMessage m1 = null;

            // count+=1;

            m1 = RpcCommunicator.instance().dequeueMessage(m2.sequence);

            if (m1 != null)
            {
                if (m1.async != null)
                {
                    m1.async.callReturn(m1, m2);
                }
                else
                {
                    lock (m1){
                        m1.result = m2;                     // assing to init-caller
                        //m1.notify();
                        m1.ev.Set();
                    }
                }
            }
        }
Пример #19
0
 protected RpcConnection(RpcAdapter adapter = null)
 {
     this.adapter = adapter;
     RpcCommunicator.instance().registerConnection(this);
 }