Example #1
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();
            }
        }
Example #2
0
        public override bool send(MemoryStream stream)
        {
            int dataLength = (int)stream.length();

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

            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;

            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);
            }

            Interlocked.Add(ref _wpos, dataLength);

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

            return(true);
        }
Example #3
0
 /// <summary>
 /// 在非主线程执行:连接服务器
 /// </summary>
 private void _asyncConnect(ConnectState state)
 {
     Dbg.DEBUG_MSG(string.Format("NetworkInterfaceBase::_asyncConnect(), will connect to '{0}:{1}' ...", state.connectIP, state.connectPort));
     onAsyncConnect(state);
 }
Example #4
0
 public virtual void onLeaveSpace()
 {
     Dbg.DEBUG_MSG(classtype + "::onLeaveSpace: " + id);
     inWorld = false;
     Event.fireOut("onLeaveSpace", new object[] { this });
 }
Example #5
0
        public override void process(byte[] datas, MessageLengthEx offset, MessageLengthEx length)
        {
            MessageLengthEx totallen = offset;

            while (length > 0 && expectSize > 0)
            {
                if (state == READ_STATE.READ_STATE_MSGID)
                {
                    if (length >= expectSize)
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, expectSize);
                        totallen    += expectSize;
                        stream.wpos += (int)expectSize;
                        length      -= expectSize;
                        msgid        = stream.readUint16();
                        stream.clear();

                        Message msg = Messages.clientMessages[msgid];

                        if (msg.msglen == -1)
                        {
                            state      = READ_STATE.READ_STATE_MSGLEN;
                            expectSize = 2;
                        }
                        else if (msg.msglen == 0)
                        {
                            // 如果是0个参数的消息,那么没有后续内容可读了,处理本条消息并且直接跳到下一条消息
                                                        #if UNITY_EDITOR
                            Dbg.profileStart(msg.name);
                                                        #endif

                            msg.handleMessage(stream);

                                                        #if UNITY_EDITOR
                            Dbg.profileEnd(msg.name);
                                                        #endif

                            state      = READ_STATE.READ_STATE_MSGID;
                            expectSize = 2;
                        }
                        else
                        {
                            expectSize = (MessageLengthEx)msg.msglen;
                            state      = READ_STATE.READ_STATE_BODY;
                        }
                    }
                    else
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, length);
                        stream.wpos += (int)length;
                        expectSize  -= length;
                        break;
                    }
                }
                else if (state == READ_STATE.READ_STATE_MSGLEN)
                {
                    if (length >= expectSize)
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, expectSize);
                        totallen    += expectSize;
                        stream.wpos += (int)expectSize;
                        length      -= expectSize;

                        msglen = stream.readUint16();
                        stream.clear();

                        // 长度扩展
                        if (msglen >= 65535)
                        {
                            state      = READ_STATE.READ_STATE_MSGLEN_EX;
                            expectSize = 4;
                        }
                        else
                        {
                            state      = READ_STATE.READ_STATE_BODY;
                            expectSize = msglen;
                        }
                    }
                    else
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, length);
                        stream.wpos += (int)length;
                        expectSize  -= length;
                        break;
                    }
                }
                else if (state == READ_STATE.READ_STATE_MSGLEN_EX)
                {
                    if (length >= expectSize)
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, expectSize);
                        totallen    += expectSize;
                        stream.wpos += (int)expectSize;
                        length      -= expectSize;

                        expectSize = stream.readUint32();
                        stream.clear();

                        state = READ_STATE.READ_STATE_BODY;
                    }
                    else
                    {
                        Array.Copy(datas, totallen, stream.data(), stream.wpos, length);
                        stream.wpos += (int)length;
                        expectSize  -= length;
                        break;
                    }
                }
                else if (state == READ_STATE.READ_STATE_BODY)
                {
                    if (length >= expectSize)
                    {
                        stream.append(datas, totallen, expectSize);
                        totallen += expectSize;
                        length   -= expectSize;

                        Message msg = Messages.clientMessages[msgid];

#if UNITY_EDITOR
                        Dbg.profileStart(msg.name);
#endif

                        msg.handleMessage(stream);
#if UNITY_EDITOR
                        Dbg.profileEnd(msg.name);
#endif

                        stream.clear();

                        state      = READ_STATE.READ_STATE_MSGID;
                        expectSize = 2;
                    }
                    else
                    {
                        stream.append(datas, totallen, length);
                        expectSize -= length;
                        break;
                    }
                }
            }
        }
Example #6
0
 public void reqRemoveAvatar(string name)
 {
     Dbg.DEBUG_MSG("Account::reqRemoveAvatar: name=" + name);
     baseCall("reqRemoveAvatar", new object[] { name });
 }
 public void reqCreateAvatar(Byte roleType, string name)
 {
     Dbg.DEBUG_MSG("Account::reqCreateAvatar: roleType=" + roleType);
     baseEntityCall.reqCreateAvatar(roleType, name);
 }
 public virtual void set_subState(object old)
 {
     Dbg.DEBUG_MSG(classtype + "::set_subState: " + getDefinedPropterty("subState"));
 }
 public virtual void set_uid(object old)
 {
     Dbg.DEBUG_MSG(classtype + "::set_uid: " + getDefinedPropterty("uid"));
 }
 public virtual void onJump()
 {
     Dbg.DEBUG_MSG(classtype + "::onJump: " + id);
     Event.fire("otherAvatarOnJump", new object[] { this });
 }
 public virtual void onRemoveSkill(Int32 skillID)
 {
     Dbg.DEBUG_MSG(classtype + "::onRemoveSkill(" + skillID + ")");
     Event.fire("onRemoveSkill", new object[] { this });
     SkillBox.inst.remove(skillID);
 }
 public virtual void set_forbids(object old)
 {
     Dbg.DEBUG_MSG(classtype + "::set_forbids: " + getDefinedPropterty("forbids"));
 }
 public void selectAvatarGame(UInt64 dbid)
 {
     Dbg.DEBUG_MSG("Account::selectAvatarGame: dbid=" + dbid);
     baseEntityCall.selectAvatarGame(dbid);
 }
 public void reqRemoveAvatar(string name)
 {
     Dbg.DEBUG_MSG("Account::reqRemoveAvatar: name=" + name);
     baseEntityCall.reqRemoveAvatar(name);
 }
Example #15
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;
            }

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

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

            try
            {
                for (var i = 0; i < method.args.Count; i++)
                {
                    if (method.args[i].isSameType(arguments[i]))
                    {
                        method.args[i].addToStream(cellMailbox.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 + ")!");
                cellMailbox.bundle = null;
                return;
            }

            cellMailbox.postMail(null);
        }
 public virtual void set_spaceUType(object old)
 {
     Dbg.DEBUG_MSG(classtype + "::set_spaceUType: " + getDefinedPropterty("spaceUType"));
 }
Example #17
0
 public void reqCreateAvatar(Byte roleType, string name)
 {
     Dbg.DEBUG_MSG("Account::reqCreateAvatar: roleType=" + roleType);
     baseCall("reqCreateAvatar", new object[] { roleType, name });
 }
Example #18
0
 public virtual void onEnterSpace()
 {
     Dbg.DEBUG_MSG(classtype + "::onEnterSpace(" + getDefinedPropterty("uid") + "): " + id);
     inWorld = true;
     Event.fireOut("onEnterSpace", new object[] { this });
 }
Example #19
0
 public void selectAvatarGame(UInt64 dbid)
 {
     Dbg.DEBUG_MSG("Account::selectAvatarGame: dbid=" + dbid);
     baseCall("selectAvatarGame", new object[] { dbid });
 }
Example #20
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);
            }
        }