ERROR_MSG() public static méthode

public static ERROR_MSG ( object s ) : void
s object
Résultat void
Exemple #1
0
        public void onCreateAvatarResult(byte retcode, object info)
        {
            if (retcode == 0)
            {
                avatars.Add((UInt64)((Dictionary <string, object>)info)["dbid"], (Dictionary <string, object>)info);
                Dbg.DEBUG_MSG("Account::onCreateAvatarResult: name=" + (string)((Dictionary <string, object>)info)["name"]);
            }
            else
            {
                Dbg.ERROR_MSG("Account::onCreateAvatarResult: retcode=" + retcode);
                if (retcode == 3)
                {
                    Dbg.ERROR_MSG("角色数量不能超过三个!");
                }
            }

            // ui event

            Event.fireOut("onCreateAvatarResult", new object[] { retcode, info, avatars });
        }
Exemple #2
0
        public Message(MessageID msgid, string msgname, Int16 length, List <Byte> msgargtypes, System.Reflection.MethodInfo msghandler)
        {
            id      = msgid;
            name    = msgname;
            msglen  = length;
            handler = msghandler;

            argtypes = new System.Reflection.MethodInfo[msgargtypes.Count];
            for (int i = 0; i < msgargtypes.Count; i++)
            {
                argtypes[i] = StreamRWBinder.bindReader(msgargtypes[i]);
                if (argtypes[i] == null)
                {
                    Dbg.ERROR_MSG("Message::Message(): bindReader(" + msgargtypes[i] + ") is error!");
                }
            }

            // Dbg.DEBUG_MSG(string.Format("Message::Message(): ({0}/{1}/{2})!",
            //	msgname, msgid, msglen));
        }
Exemple #3
0
        public override void onCreateAvatarResult(byte retcode, AVATAR_INFO info)
        {
            if (retcode == 0)
            {
                avatars.Add(info.dbid, info);
                Dbg.DEBUG_MSG("Account::onCreateAvatarResult: name=" + info.name);
            }
            else
            {
                Dbg.ERROR_MSG("Account::onCreateAvatarResult: retcode=" + retcode);
                if (retcode == 3)
                {
                    Dbg.ERROR_MSG("角色数量不能超过三个!");
                }
            }

            // ui event

            Event.fireOut("onCreateAvatarResult", new object[] { retcode, info, avatars });
        }
Exemple #4
0
        public void onCreateAvatarResult(Byte retcode, object info)
        {
            if (retcode == 0)
            {
                avatars.Add((UInt64)((Dictionary <string, object>)info)["dbid"], (Dictionary <string, object>)info);
                Dbg.DEBUG_MSG("Account::onCreateAvatarResult: name=" + (string)((Dictionary <string, object>)info)["name"]);
            }
            else
            {
                Dbg.ERROR_MSG("Account::onCreateAvatarResult: retcode=" + retcode);
            }

            // ui event
            KBS_CreateAvatarResult e = new KBS_CreateAvatarResult();

            e.retcode    = retcode;
            e.info       = info;
            e.avatarList = avatars;
            KBEvent.fireOut(KET.onCreateAvatarResult, e);
        }
Exemple #5
0
        public static void processNocacheOutEvent()
        {
            while (nocache_Fireout.Count > 0)
            {
                EventObj eobj = nocache_Fireout.First.Value;
                try
                {
                    eobj.info.method.Invoke(eobj.info.obj, eobj.args);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG("Event::processOutEvents: event=" + eobj.info.funcname + "\n" + e.ToString());
                }

                if (nocache_Fireout.Count > 0)
                {
                    nocache_Fireout.RemoveFirst();
                }
            }
        }
Exemple #6
0
        public void send(NetworkInterface networkInterface)
        {
            fini(true);

            if (networkInterface.valid())
            {
                for (int i = 0; i < streamList.Count; i++)
                {
                    stream = streamList[i];
                    networkInterface.send(stream.getbuffer());
                }
            }
            else
            {
                Dbg.ERROR_MSG("Bundle::send: networkInterface invalid!");
            }

            streamList.Clear();
            stream = new MemoryStream();
        }
Exemple #7
0
        public static void processInEvents()
        {
            monitor_Enter(events_in);

            if (firedEvents_in.Count > 0)
            {
                var iter = firedEvents_in.GetEnumerator();
                while (iter.MoveNext())
                {
                    doingEvents_in.AddLast(iter.Current);
                }

                firedEvents_in.Clear();
            }

            monitor_Exit(events_in);

            while (doingEvents_in.Count > 0)
            {
                EventObj eobj = doingEvents_in.First.Value;

                //Debug.Log("processInEvents:" + eobj.info.funcname + "(" + eobj.info + ")");
                //foreach(object v in eobj.args)
                //{
                //	Debug.Log("processInEvents:args=" + v);
                //}
                try
                {
                    eobj.info.method.Invoke(eobj.info.obj, eobj.args);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG("Event::processInEvents: event=" + eobj.info.method.DeclaringType.FullName + "::" + eobj.info.funcname + "\n" + e.ToString());
                }

                if (doingEvents_in.Count > 0)
                {
                    doingEvents_in.RemoveFirst();
                }
            }
        }
Exemple #8
0
        public bool loadAll()
        {
            byte[] kbengine_digest = loadFile(_persistentDataPath, "kbengine.digest." + _getSuffixBase(), false);
            if (kbengine_digest.Length <= 0)
            {
                clearMessageFiles();
                return(false);
            }

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            _digest = encoding.GetString(kbengine_digest);

            byte[] loginapp_onImportClientMessages = loadFile(_persistentDataPath, "loginapp_clientMessages." + _getSuffix(), false);

            byte[] baseapp_onImportClientMessages = loadFile(_persistentDataPath, "baseapp_clientMessages." + _getSuffix(), false);

            byte[] onImportServerErrorsDescr = loadFile(_persistentDataPath, "serverErrorsDescr." + _getSuffix(), false);

            byte[] onImportClientEntityDef = loadFile(_persistentDataPath, "clientEntityDef." + _getSuffix(), false);

            if (loginapp_onImportClientMessages.Length > 0 && baseapp_onImportClientMessages.Length > 0)
            {
                try
                {
                    if (!KBEngineApp.app.importMessagesFromMemoryStream(loginapp_onImportClientMessages,
                                                                        baseapp_onImportClientMessages, onImportClientEntityDef, onImportServerErrorsDescr))
                    {
                        clearMessageFiles();
                    }
                    return(false);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG("PersistentInofs::loadAll(): is error(" + e.ToString() + ")!");
                    clearMessageFiles();
                    return(false);
                }
            }

            return(true);
        }
Exemple #9
0
        public static void processOutEvents()
        {
            monitor_Enter(events_out);

            if (firedEvents_out.Count > 0)
            {
                foreach (EventObj evt in firedEvents_out)
                {
                    doingEvents_out.AddLast(evt);
                }

                firedEvents_out.Clear();
            }

            monitor_Exit(events_out);

            while (doingEvents_out.Count > 0 && !_isPauseOut)
            {
                EventObj eobj = doingEvents_out.First.Value;

                //Debug.Log("processOutEvents:" + eobj.info.funcname + "(" + eobj.info + ")");
                //foreach(object v in eobj.args)
                //{
                //	Debug.Log("processOutEvents:args=" + v);
                //}
                try
                {
                    eobj.info.method.Invoke(eobj.info.obj, eobj.args);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG("Event::processOutEvents: event=" + eobj.info.funcname + "\n" + e.ToString());
                }

                if (doingEvents_out.Count > 0)
                {
                    doingEvents_out.RemoveFirst();
                }
            }
        }
Exemple #10
0
        public static void fire(string eventname, object[] args)
        {
            Monitor.Enter(events);
            List <Pair> lst = null;

            if (!events.TryGetValue(eventname, out lst))
            {
                Dbg.ERROR_MSG("Event::fire: event(" + eventname + ") not found!");
                Monitor.Exit(events);
                return;
            }

            for (int i = 0; i < lst.Count; i++)
            {
                EventObj eobj = new EventObj();
                eobj.info = lst[i];
                eobj.args = args;
                firedEvents.Add(eobj);
            }

            Monitor.Exit(events);
        }
Exemple #11
0
        public Message(MessageID msgid, string msgname, Int16 length, sbyte argstype, List <Byte> msgargtypes, System.Reflection.MethodInfo msghandler)
        {
            id       = msgid;
            name     = msgname;
            msglen   = length;
            handler  = msghandler;
            argsType = argstype;

            // 对该消息的所有参数绑定反序列化方法,改方法能够将二进制流转化为参数需要的值
            // 在服务端下发消息数据时会用到
            argtypes = new KBEDATATYPE_BASE[msgargtypes.Count];
            for (int i = 0; i < msgargtypes.Count; i++)
            {
                if (!EntityDef.id2datatypes.TryGetValue(msgargtypes[i], out argtypes[i]))
                {
                    Dbg.ERROR_MSG("Message::Message(): argtype(" + msgargtypes[i] + ") is not found!");
                }
            }

            // Dbg.DEBUG_MSG(string.Format("Message::Message(): ({0}/{1}/{2})!",
            //	msgname, msgid, msglen));
        }
        private static void _onSent(IAsyncResult ar)
        {
            // Retrieve the socket from the state object.
            PacketSender state = (PacketSender)ar.AsyncState;

            try
            {
                // 由于多线程问题,networkInterface可能已被丢弃了
                // 例如:在连接loginapp之后自动开始连接到baseapp之前会先关闭并丢弃networkInterface
                if (!state.networkInterface().valid())
                {
                    return;
                }

                Socket client = state.networkInterface().sock();

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);

                int spos = Interlocked.Add(ref state._spos, bytesSent);

                // 如果数据没有发送完毕需要继续投递发送
                if (spos != Interlocked.Add(ref state._wpos, 0))
                {
                    state._startSend();
                }
                else
                {
                    // 所有数据发送完毕了
                    Interlocked.Exchange(ref state._sending, 0);
                }
            }
            catch (Exception e)
            {
                Dbg.ERROR_MSG(string.Format("PacketSender::_processSent(): is error({0})!", e.ToString()));
                Event.fireIn("_closeNetwork", new object[] { state.networkInterface() });
                Interlocked.Exchange(ref state._sending, 0);
            }
        }
        public static void processInEvents()
        {
            Monitor.Enter(events_in);

            if (firedEvents_in.Count > 0)
            {
                foreach (EventObj evt in firedEvents_in)
                {
                    doingEvents_in.AddLast(evt);
                }

                firedEvents_in.Clear();
            }

            Monitor.Exit(events_in);

            while (doingEvents_in.Count > 0)
            {
                EventObj eobj = doingEvents_in.First.Value;

                //Debug.Log("processInEvents:" + eobj.info.funcname + "(" + eobj.info + ")");
                //foreach(object v in eobj.args)
                //{
                //	Debug.Log("processInEvents:args=" + v);
                //}
                try
                {
                    eobj.info.method.Invoke(eobj.info.obj, eobj.args);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG(e.ToString());
                    Dbg.ERROR_MSG("Event::processInEvents: event=" + eobj.info.funcname);
                }

                doingEvents_in.RemoveFirst();
            }
        }
        public override bool isSameType(object v)
        {
            if (vtype.GetType().BaseType.ToString() != "KBEngine.KBEDATATYPE_BASE")
            {
                Dbg.ERROR_MSG(string.Format("KBEDATATYPE_ARRAY::isSameType: has not bind!"));
                return(false);
            }

            if (v == null || v.GetType() != typeof(List <object>))
            {
                return(false);
            }

            for (int i = 0; i < ((List <object>)v).Count; i++)
            {
                if (!((KBEDATATYPE_BASE)vtype).isSameType(((List <object>)v)[i]))
                {
                    return(false);
                }
            }

            return(true);
        }
        public bool send(byte[] datas)
        {
            if (!valid())
            {
                throw new ArgumentException("invalid socket!");
            }

            if (_packetSender == null)
            {
                _packetSender = new PacketSender(this);
            }

            try
            {
                return(_packetSender.send(datas));
            }
            catch (SocketException err)
            {
                Dbg.ERROR_MSG(string.Format("NetworkInterface::send(): socket error(" + err.ErrorCode + ")!"));
                close();
            }

            return(false);
        }
Exemple #16
0
        public static void processOutEvents()
        {
            monitor_Enter(events_out);

            if (firedEvents_out.Count > 0)
            {
                var iter = firedEvents_out.GetEnumerator();
                while (iter.MoveNext())
                {
                    doingEvents_out.AddLast(iter.Current);
                }
                firedEvents_out.Clear();
            }

            monitor_Exit(events_out);
            List <EventObj> eobjList = new List <EventObj>();

            while (doingEvents_out.Count > 0 && !_isPauseOut)
            {
                EventObj eobj = doingEvents_out.First.Value;

                try
                {
                    Instance.Get <NetHelper>().Add(eobj);
                }
                catch (Exception e)
                {
                    Dbg.ERROR_MSG("Event::processOutEvents: event=" + eobj.info.funcname + "\n" + e.ToString());
                }

                if (doingEvents_out.Count > 0)
                {
                    doingEvents_out.RemoveFirst();
                }
            }
        }
Exemple #17
0
        void sendImm(NetworkInterface networkInterface, uint fId)
        {
            fini(true);
            Debug.Log("message Number " + streamList.Count);
            //bool resp = false;
            if (networkInterface.valid())
            {
                for (int i = 0; i < streamList.Count; i++)
                {
                    stream = streamList[i];
                    networkInterface.send(stream.getbuffer(), delegate(Packet p) {
                        //par.packet = p;
                        //resp = true;
                    }, fId);
                }
            }
            else
            {
                Dbg.ERROR_MSG("Bundle::send: networkInterface invalid!");
            }

            streamList.Clear();
            stream = new MemoryStream();
        }
Exemple #18
0
        public void cellCall(string methodname, object[] arguments)
        {
            if (KBEngineApp.app.currserver == "loginapp")
            {
                Dbg.ERROR_MSG(classtype + "::cellCall(" + methodname + "), currserver=!" + KBEngineApp.app.currserver);
                return;
            }

            Method method   = EntityDef.moduledefs[classtype].cell_methods[methodname];
            UInt16 methodID = method.methodUtype;

            if (arguments.Length != method.args.Count)
            {
                Dbg.ERROR_MSG(classtype + "::cellCall(" + methodname + "): args(" + (arguments.Length) + "!= " + method.args.Count + ") size is error!");
                return;
            }

            cellMailbox.newMail();
            cellMailbox.bundle.writeUint16(methodID);

            try
            {
                for (var i = 0; i < method.args.Count; i++)
                {
                    method.args[i].addToStream(cellMailbox.bundle, arguments[i]);
                }
            }
            catch (Exception e)
            {
                Dbg.ERROR_MSG(classtype + "::cellCall(" + methodname + "): args is error(" + e.Message + ")!");
                cellMailbox.bundle = null;
                return;
            }

            cellMailbox.postMail(null);
        }
Exemple #19
0
        public void send(byte[] datas)
        {
            if (socket_ == null || socket_.Connected == false)
            {
                throw new ArgumentException("invalid socket!");
            }

            if (datas == null || datas.Length == 0)
            {
                throw new ArgumentException("invalid datas!");
            }

            try
            {
                socket_.Send(datas);
            }
            catch (SocketException err)
            {
                if (err.ErrorCode == 10054 || err.ErrorCode == 10053)
                {
                    Dbg.DEBUG_MSG(string.Format("NetworkInterface::send(): disable connect!"));

                    if (socket_ != null && socket_.Connected)
                    {
                        socket_.Close();
                    }

                    socket_ = null;
                    Event.fireAll("onDisableConnect", new object[] {});
                }
                else
                {
                    Dbg.ERROR_MSG(string.Format("NetworkInterface::send(): socket error(" + err.ErrorCode + ")!"));
                }
            }
        }
Exemple #20
0
        public void send(NetworkInterfaceBase networkInterface)
        {
            fini(true);

            if (networkInterface.valid())
            {
                for (int i = 0; i < streamList.Count; i++)
                {
                    MemoryStream tempStream = streamList[i];
                    networkInterface.send(tempStream);
                }
            }
            else
            {
                Dbg.ERROR_MSG("Bundle::send: networkInterface invalid!");
            }

            // 我们认为,发送完成,就视为这个bundle不再使用了,
            // 所以我们会把它放回对象池,以减少垃圾回收带来的消耗,
            // 如果需要继续使用,应该重新Bundle.createObject(),
            // 如果外面不重新createObject()而直接使用,就可能会出现莫名的问题,
            // 仅以此备注,警示使用者。
            reclaimObject();
        }
        public void _onConnectStatus(string error)
        {
            KBEngine.Event.deregisterIn(this);

            bool success = (error == "");

            if (success)
            {
                Dbg.INFO_MSG(string.Format("NetworkInterface::_onConnectStatus(), connected to {0}", sock().RemoteEndPoint.ToString()));
                _packetReceiver = new PacketReceiver(this);
                _packetReceiver.startRecv();
            }
            else
            {
                Dbg.ERROR_MSG(string.Format("NetworkInterface::_onConnectStatus(), connect is error! ip: {0}:{1}, err: {2}", _connectIP, _connectPort, error));
            }

            Event.fireAll("onConnectStatus", new object[] { success });

            if (_connectCB != null)
            {
                _connectCB(_connectIP, _connectPort, success, _userData);
            }
        }
Exemple #22
0
        public void _onConnectionState(ConnectState state)
        {
            KBEngine.Event.deregisterIn(this);

            bool success = (state.error == "" && valid());

            if (success)
            {
                Dbg.DEBUG_MSG(string.Format("NetworkInterface::_onConnectionState(), connect to {0} is success!", state.socket.RemoteEndPoint.ToString()));
                _packetReceiver = new PacketReceiver(this);
                _packetReceiver.startRecv();
            }
            else
            {
                Dbg.ERROR_MSG(string.Format("NetworkInterface::_onConnectionState(), connect is error! ip: {0}:{1}, err: {2}", state.connectIP, state.connectPort, state.error));
            }

            KBELuaUtil.CallMethod("Event", "Brocast", new object[] { "onConnectionState", success });

            if (state.connectCB != null)
            {
                state.connectCB(state.connectIP, state.connectPort, success, state.userData);
            }
        }
Exemple #23
0
        public void cellCall(string methodname, params object[] arguments)
        {
            if (KBEngineApp.app.currserver == "loginapp")
            {
                Dbg.ERROR_MSG(className + "::cellCall(" + methodname + "), currserver=!" + KBEngineApp.app.currserver);
                return;
            }

            ScriptModule module = null;

            if (!EntityDef.moduledefs.TryGetValue(className, out module))
            {
                Dbg.ERROR_MSG("entity::cellCall:  entity-module(" + className + ") error, can not find from EntityDef.moduledefs!");
                return;
            }

            Method method = null;

            if (!module.cell_methods.TryGetValue(methodname, out method))
            {
                Dbg.ERROR_MSG(className + "::cellCall(" + methodname + "), not found method!");
                return;
            }

            UInt16 methodID = method.methodUtype;

            if (arguments.Length != method.args.Count)
            {
                Dbg.ERROR_MSG(className + "::cellCall(" + methodname + "): args(" + (arguments.Length) + "!= " + method.args.Count + ") size is error!");
                return;
            }

            EntityCall cellEntityCall = getCellEntityCall();

            if (cellEntityCall == null)
            {
                Dbg.ERROR_MSG(className + "::cellCall(" + methodname + "): no cell!");
                return;
            }

            cellEntityCall.newCall();
            cellEntityCall.bundle.writeUint16(0);
            cellEntityCall.bundle.writeUint16(methodID);

            try
            {
                for (var i = 0; i < method.args.Count; i++)
                {
                    if (method.args[i].isSameType(arguments[i]))
                    {
                        method.args[i].addToStream(cellEntityCall.bundle, arguments[i]);
                    }
                    else
                    {
                        throw new Exception("arg" + i + ": " + method.args[i].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Dbg.ERROR_MSG(className + "::cellCall(" + methodname + "): args is error(" + e.Message + ")!");
                cellEntityCall.bundle = null;
                return;
            }

            cellEntityCall.sendCall(null);
        }
Exemple #24
0
        public override bool send(MemoryStream stream)
        {
            int dataLength = (int)stream.length();

            if (dataLength <= 0)
            {
                return(true);
            }

            Monitor.Enter(_sending);
            if (!_sending)
            {
                if (_wpos == _spos)
                {
                    _wpos = 0;
                    _spos = 0;
                }
            }

            int t_spos  = _spos;
            int space   = 0;
            int tt_wpos = _wpos % _buffer.Length;
            int tt_spos = t_spos % _buffer.Length;

            if (tt_wpos >= tt_spos)
            {
                space = _buffer.Length - tt_wpos + tt_spos - 1;
            }
            else
            {
                space = tt_spos - tt_wpos - 1;
            }

            if (dataLength > space)
            {
                Dbg.ERROR_MSG("PacketSenderTCP::send(): no space, Please adjust 'SEND_BUFFER_MAX'! data(" + dataLength
                              + ") > space(" + space + "), wpos=" + _wpos + ", spos=" + t_spos);

                return(false);
            }

            int expect_total = tt_wpos + dataLength;

            if (expect_total <= _buffer.Length)
            {
                Array.Copy(stream.data(), stream.rpos, _buffer, tt_wpos, dataLength);
            }
            else
            {
                int remain = _buffer.Length - tt_wpos;
                Array.Copy(stream.data(), stream.rpos, _buffer, tt_wpos, remain);
                Array.Copy(stream.data(), stream.rpos + remain, _buffer, 0, expect_total - _buffer.Length);
            }

            _wpos += dataLength;

            if (!_sending)
            {
                _sending = true;
                Monitor.Exit(_sending);

                _startSend();
            }
            else
            {
                Monitor.Exit(_sending);
            }

            return(true);
        }
Exemple #25
0
        public override bool recv(MessageReader reader, byte[] buffer, UInt32 rpos, UInt32 len)
        {
            if (!_blowfish.isGood())
            {
                Dbg.ERROR_MSG("BlowfishFilter::recv: Dropping packet, due to invalid filter");
                return(false);
            }

            if (_packet.length() == 0 && len >= MIN_PACKET_SIZE && BitConverter.ToUInt16(buffer, (int)rpos) - 1 == len - 3)
            {
                int packLen = BitConverter.ToUInt16(buffer, (int)rpos) - 1;
                int padSize = buffer[rpos + 2];

                decrypt(buffer, (int)(rpos + 3), (int)(len - 3));

                int length = packLen - padSize;
                if (reader != null)
                {
                    reader.process(buffer, rpos + 3, (UInt32)length);
                }

                return(true);
            }

            _packet.append(buffer, rpos, len);

            while (_packet.length() > 0)
            {
                UInt32 currLen = 0;
                int    oldwpos = 0;
                if (_packLen <= 0)
                {
                    // 如果满足一个最小包则尝试解包, 否则缓存这个包待与下一个包合并然后解包
                    if (_packet.length() >= MIN_PACKET_SIZE)
                    {
                        _packLen = _packet.readUint16();
                        _padSize = _packet.readUint8();

                        _packLen -= 1;

                        if (_packet.length() > _packLen)
                        {
                            currLen      = (UInt32)(_packet.rpos + _packLen);
                            oldwpos      = _packet.wpos;
                            _packet.wpos = (int)currLen;
                        }
                        else if (_packet.length() < _packLen)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    // 如果上一次有做过解包行为但包还没有完整则继续处理
                    // 如果包是完整的下面流程会解密, 如果有多余的内容需要将其剪裁出来待与下一个包合并
                    if (_packet.length() > _packLen)
                    {
                        currLen      = (UInt32)(_packet.rpos + _packLen);
                        oldwpos      = _packet.wpos;
                        _packet.wpos = (int)currLen;
                    }
                    else if (_packet.length() < _packLen)
                    {
                        return(false);
                    }
                }

                decrypt(_packet);
                _packet.wpos -= _padSize;

                // 上面的流程能保证wpos之后不会有多余的包
                // 如果有多余的包数据会放在_recvStream
                if (reader != null)
                {
                    reader.process(_packet.data(), (UInt32)_packet.rpos, _packet.length());
                }

                if (currLen > 0)
                {
                    _packet.rpos = (int)currLen;
                    _packet.wpos = oldwpos;
                }
                else
                {
                    _packet.clear();
                }

                _packLen = 0;
                _padSize = 0;
            }

            return(true);
        }
Exemple #26
0
        public void recv()
        {
            if (socket_ == null || socket_.Connected == false)
            {
                throw new ArgumentException("invalid socket!");
            }

            if (socket_.Poll(0, SelectMode.SelectRead))
            {
                if (socket_ == null || socket_.Connected == false)
                {
                    Dbg.WARNING_MSG("invalid socket!");
                    return;
                }

                int successReceiveBytes = 0;

                try
                {
                    successReceiveBytes = socket_.Receive(_datas, MemoryStream.BUFFER_MAX, 0);
                }
                catch (SocketException err)
                {
                    if (err.ErrorCode == 10054 || err.ErrorCode == 10053)
                    {
                        Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): disable connect!"));

                        if (socket_ != null && socket_.Connected)
                        {
                            socket_.Close();
                        }

                        socket_ = null;
                    }
                    else
                    {
                        Dbg.ERROR_MSG(string.Format("NetworkInterface::recv(): socket error(" + err.ErrorCode + ")!"));
                    }

                    return;
                }

                if (successReceiveBytes > 0)
                {
                    //	Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): size={0}!", successReceiveBytes));
                }
                else if (successReceiveBytes == 0)
                {
                    Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): disable connect!"));
                    if (socket_ != null && socket_.Connected)
                    {
                        socket_.Close();
                    }
                    socket_ = null;
                }
                else
                {
                    Dbg.ERROR_MSG(string.Format("NetworkInterface::recv(): socket error!"));

                    if (socket_ != null && socket_.Connected)
                    {
                        socket_.Close();
                    }
                    socket_ = null;

                    return;
                }
                Debug.Log("success received Data " + successReceiveBytes);
                msgReader.process(_datas, (MessageLength)successReceiveBytes, flowHandlers);
            }
        }
Exemple #27
0
        protected override void onAsyncConnect(ConnectState state)
        {
            try
            {
                //state.socket.Connect(state.connectIP, state.connectPort);

                byte[] helloPacket = System.Text.Encoding.ASCII.GetBytes(UDP_HELLO);
                state.socket.SendTo(helloPacket, helloPacket.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(state.connectIP), state.connectPort));

                ArrayList readList = new ArrayList();
                readList.Add(state.socket);
                Socket.Select(readList, null, null, 3000000);

                if (readList.Count > 0)
                {
                    byte[] buffer = new byte[UDP_PACKET_MAX];
                    int    length = state.socket.Receive(buffer);

                    if (length <= 0)
                    {
                        Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! receive hello-ack error!", state.connectIP, state.connectPort));
                        state.error = "receive hello-ack error!";
                    }
                    else
                    {
                        MemoryStream stream = new MemoryStream();
                        Array.Copy(buffer, 0, stream.data(), stream.wpos, length);
                        stream.wpos = length;
                        string helloAck      = stream.readString();
                        string versionString = stream.readString();
                        uint   conv          = stream.readUint32();

                        if (helloAck != UDP_HELLO_ACK)
                        {
                            Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! receive hello-ack({2}!={3}) mismatch!",
                                                        state.connectIP, state.connectPort, helloAck, UDP_HELLO_ACK));

                            state.error = "hello-ack mismatch!";
                        }
                        else if (KBEngineApp.app.serverVersion != versionString)
                        {
                            Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! version({2}!={3}) mismatch!",
                                                        state.connectIP, state.connectPort, versionString, KBEngineApp.app.serverVersion));

                            state.error = "version mismatch!";
                        }
                        else if (conv == 0)
                        {
                            Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), failed to connect to '{0}:{1}'! conv is 0!",
                                                        state.connectIP, state.connectPort));

                            state.error = "kcp conv error!";
                        }

                        ((NetworkInterfaceKCP)state.networkInterface).connID = conv;
                    }
                }
                else
                {
                    Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), connect to '{0}:{1}' timeout!'", state.connectIP, state.connectPort));
                    state.error = "timeout!";
                }
            }
            catch (Exception e)
            {
                Dbg.ERROR_MSG(string.Format("NetworkInterfaceKCP::_asyncConnect(), connect to '{0}:{1}' fault! error = '{2}'", state.connectIP, state.connectPort, e));
                state.error = e.ToString();
            }
        }
        public bool send(byte[] datas)
        {
            if (datas.Length <= 0)
            {
                return(true);
            }

            bool startSend = false;

            if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0)
            {
                startSend = true;
                if (_wpos == _spos)
                {
                    _wpos = 0;
                    _spos = 0;
                }
            }

            int t_spos  = Interlocked.Add(ref _spos, 0);
            int space   = 0;
            int tt_wpos = _wpos % _buffer.Length;
            int tt_spos = t_spos % _buffer.Length;

            if (tt_wpos >= tt_spos)
            {
                space = _buffer.Length - tt_wpos + tt_spos - 1;
            }
            else
            {
                space = tt_spos - tt_wpos - 1;
            }

            if (datas.Length > space)
            {
                Dbg.ERROR_MSG("PacketSender::send(): no space, Please adjust 'SEND_BUFFER_MAX'! data(" + datas.Length
                              + ") > space(" + space + "), wpos=" + _wpos + ", spos=" + t_spos);

                return(false);
            }

            int expect_total = tt_wpos + datas.Length;

            if (expect_total <= _buffer.Length)
            {
                Array.Copy(datas, 0, _buffer, tt_wpos, datas.Length);
            }
            else
            {
                int remain = _buffer.Length - tt_wpos;
                Array.Copy(datas, 0, _buffer, tt_wpos, remain);
                Array.Copy(datas, remain, _buffer, 0, expect_total - _buffer.Length);
            }

            Interlocked.Add(ref _wpos, datas.Length);

            if (startSend)
            {
                _startSend();
            }

            return(true);
        }
        public bool send(MemoryStream stream)
        {
            int dataLength = (int)stream.length();

            if (dataLength <= 0)
            {
                return(true);
            }

            //如果没有在发送的数据,且写位置和发送位置一样,则把写位置和发送位置都置0
            if (0 == Interlocked.Add(ref _sending, 0))
            {
                if (_wpos == _spos)
                {
                    _wpos = 0;
                    _spos = 0;
                }
            }

            int t_spos  = Interlocked.Add(ref _spos, 0);
            int space   = 0;
            int tt_wpos = _wpos % _buffer.Length;
            int tt_spos = t_spos % _buffer.Length;

            //                 _____________________________________________________________________________________________________
            // _buffer = | 000000000000000000000000000000000 0 00000000000000000000000000000000000 0 00000000000000000000000000000 |
            //                                                                                     ^                                                                        ^
            //                                                                                 _spos                                                                _wpos
            //                <----------------space----------------------> <----------------data-------------------------> <----------------space---------------->
            if (tt_wpos >= tt_spos)
            {
                space = _buffer.Length - tt_wpos + tt_spos - 1;
            }
            else
            {
                space = tt_spos - tt_wpos - 1;
            }

            if (dataLength > space)
            {
                Dbg.ERROR_MSG("PacketSender::send(): no space, Please adjust 'SEND_BUFFER_MAX'! data(" + dataLength
                              + ") > space(" + space + "), wpos=" + _wpos + ", spos=" + t_spos);

                return(false);
            }

            int expect_total = tt_wpos + dataLength;

            if (expect_total <= _buffer.Length)
            {
                Array.Copy(stream.data(), stream.rpos, _buffer, tt_wpos, dataLength);
            }
            else
            {
                int remain = _buffer.Length - tt_wpos;
                Array.Copy(stream.data(), stream.rpos, _buffer, tt_wpos, remain);
                Array.Copy(stream.data(), stream.rpos + remain, _buffer, 0, expect_total - _buffer.Length);
            }

            Interlocked.Add(ref _wpos, dataLength);

            if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0)
            {
                _startSend();
            }

            return(true);
        }
Exemple #30
0
        public void recv()
        {
            if (socket_ == null || socket_.Connected == false)
            {
                throw new ArgumentException("invalid socket!");
            }

            if (socket_.Poll(1000, SelectMode.SelectRead))
            {
                if (socket_ == null || socket_.Connected == false)
                {
                    Dbg.WARNING_MSG("invalid socket!");
                    return;
                }

                byte[] datas = new byte[MemoryStream.BUFFER_MAX];

                int successReceiveBytes = 0;

                try
                {
                    successReceiveBytes = socket_.Receive(datas, MemoryStream.BUFFER_MAX, 0);
                }
                catch (SocketException err)
                {
                    if (err.ErrorCode == 10054 || err.ErrorCode == 10053)
                    {
                        Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): disable connect!"));
                        if (socket_ != null && socket_.Connected)
                        {
                            socket_.Close();
                        }
                        socket_ = null;
                        Event.fire("onDisableConnect", new object[] {});
                    }
                    else
                    {
                        Dbg.ERROR_MSG(string.Format("NetworkInterface::recv(): socket error(" + err.ErrorCode + ")!"));
                    }
                }

                if (successReceiveBytes > 0)
                {
                    //	Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): size={0}!", successReceiveBytes));
                }
                else if (successReceiveBytes == 0)
                {
                    Dbg.DEBUG_MSG(string.Format("NetworkInterface::recv(): disable connect!"));
                    if (socket_ != null && socket_.Connected)
                    {
                        socket_.Close();
                    }
                    socket_ = null;
                }
                else
                {
                    Dbg.ERROR_MSG(string.Format("NetworkInterface::recv(): socket error!"));
                }

                msgReader.process(datas, (MessageLength)successReceiveBytes);
            }
        }