Esempio n. 1
0
        void init_kcp(UInt32 conv)
        {
            mKcp = new KCP(conv, (byte[] buf, int size) =>
            {
                mUdpClient.Send(buf, size);
            });

            // fast mode.
            mKcp.NoDelay(1, 10, 2, 1);
            mKcp.WndSize(128, 128);
        }
Esempio n. 2
0
 public void Clean()
 {
     Debuger.Log();
     if (m_Kcp != null)
     {
         m_Kcp.Dispose();
         m_Kcp = null;
     }
     m_RecvListener = null;
     Close();
 }
Esempio n. 3
0
        //------------------------------------------------------------
        #region 构造相关
        public void Init(uint sid)
        {
            Debuger.Log("sid:{0}", sid);
            m_sid = sid;
            m_TempSendData.sid = sid;
            m_TempSendData.msgs.Add(new FSPMessage());

            m_Kcp = new KCP(m_sid, HandleKcpSend);
            m_Kcp.NoDelay(1, 10, 2, 1);
            m_Kcp.WndSize(128, 128);
        }
Esempio n. 4
0
 public void Clean()
 {
     kcp?.Dispose();
     kcp            = null;
     recvListener   = null;
     sendBufferTemp = null;
     recvBufferTemp = null;
     tempSendData   = null;
     recvBuffQueue.Clear();
     recvBuffQueue = null;
     Close();
 }
Esempio n. 5
0
    void reset_state()
    {
        mNeedUpdateFlag = false;
        mNextUpdateTime = 0;

        mInConnectStage      = false;
        mConnectSucceed      = false;
        mConnectStartTime    = 0;
        mLastSendConnectTime = 0;
        mRecvQueue.Clear();
        mKcp = null;
    }
Esempio n. 6
0
    void init_kcp(UInt32 conv)
    {
        m_Kcp = new KCP(conv, null);
        m_Kcp.SetOutput((byte[] buf, int size, object user) =>
        {
            m_KCPServer.Send(this, buf, size);
        });

        // fast mode.
        m_Kcp.NoDelay(1, 20, 2, 1);
        m_Kcp.WndSize(128, 128);
    }
Esempio n. 7
0
        public KCPSession(uint sid, Action <ISession, byte[], int> sender, ISessionListener listener)
        {
            Debuger.Log("sid:{0}", sid);

            m_id       = sid;
            m_sender   = sender;
            m_listener = listener;

            m_Kcp = new KCP(sid, HandleKcpSend);
            m_Kcp.NoDelay(1, 10, 2, 1);
            m_Kcp.WndSize(128, 128);
        }
Esempio n. 8
0
    void init_kcp(UInt32 conv)
    {
        conv = 1;
        mKcp = new KCP(conv, (byte[] buf, int size) =>
        {
            base.Send(buf, 0, buf.Length);
        });

        // fast mode.
        mKcp.NoDelay(1, 10, 2, 1);
        mKcp.WndSize(128, 128);
    }
Esempio n. 9
0
        public FSPSession(uint sid, Action <IPEndPoint, byte[], int> sender)
        {
            Debuger.Log();
            m_id     = sid;
            m_sender = sender;

            m_Kcp = new KCP(sid, HandleKcpSend);
            m_Kcp.NoDelay(1, 10, 2, 1);
            m_Kcp.WndSize(128, 128);

            m_active = true;
        }
Esempio n. 10
0
        private void OnRecive(IAsyncResult ar)
        {
            if (client == null)
            {
                return;
            }

            try
            {
                byte[] buf = client.EndReceive(ar, ref remoteEndPoint);

                if (buf == null || buf.Length <= 0)
                {
                    Debug.LogError("Recive buff is null");
                    return;
                }

                if (buf.Length < KCP.IKCP_OVERHEAD)
                {
                    return;
                }

                UInt32 ts   = 0;
                UInt32 conv = 0;
                byte   cmd  = 0;

                KCP.ikcp_decode32u(buf, 0, ref conv);

                if (this.conv != conv)
                {
                    return;
                }

                KCP.ikcp_decode8u(buf, 4, ref cmd);

                if (cmd == KCP.IKCP_CMD_ACK)
                {
                    //拦截ack包中的时间戳,作为ping值计算
                    KCP.ikcp_decode32u(buf, 8, ref ts);
                    App.Trigger(EventName.Ping, (SystemTime.Clock() - ts));
                }

                //推进kcp处理
                channel.Input(buf);
                client.BeginReceive(OnRecive, null);
            }
            catch (Exception)
            {
                Debug.LogError("host is closed.");
                Dispose();
            }
        }
Esempio n. 11
0
        public KCPObject(int user)
        {
            this.user = user;

            kcp = KCP.KcpCreate(0xAABBCCDD, new IntPtr(user));

            kcpOutput = KCPOutput;
            KCP.KcpSetoutput(this.kcp, kcpOutput);

            // fast mode
            KCP.KcpNodelay(kcp, 1, 10, 2, 1);
            KCP.KcpWndsize(kcp, 128, 128);
        }
Esempio n. 12
0
 public void Init(uint sessionid)
 {
     sessionID              = sessionid;
     sendBufferTemp         = new byte[4096];
     recvBufferTemp         = new byte[4096];
     tempSendData           = new FSPDataCToS();
     recvBuffQueue          = new SwitchQueue <byte[]>();
     tempSendData.sessionID = sessionid;
     tempSendData.msg       = new FSPMessage();
     kcp = new KCP(sessionid, HandleKcpSend);
     kcp.NoDelay(1, 10, 2, 1);
     kcp.WndSize(128, 128);
 }
Esempio n. 13
0
    /// <summary>
    /// 和Update同一个线程调用
    /// </summary>
    internal void process_recv_queue(byte[] datas)
    {
#if DEV
        IRQLog.AppLog.Log(this.m_netIndex.ToString() + ",接收1");
#endif
        if (m_Kcp != null && datas != null)
        {
            m_Kcp.Input(datas);

            m_NeedUpdateFlag = true;

            for (var size = m_Kcp.PeekSize(); size > 0; size = m_Kcp.PeekSize())
            {
                byte[] buffer;
                buffer = (UdpLibConfig.UseBytePool ? m_KCPServer.BytePool.Rent(size) : new byte[size]);
                try
                {
                    if (m_Kcp.Recv(buffer) > 0)
                    {
                        m_LastRecvTimestamp = m_KCPServer.m_watch.Elapsed;

                        uint key = 0;
                        KCP.ikcp_decode32u(buffer, 0, ref key);
                        if (m_KCPServer.IsClientKeyCorrect(this.m_netIndex, (int)key) == false)
                        {
#if DEBUG
                            Console.WriteLine("index:{0} key 不对", this.m_netIndex);
#endif
                            m_KCPServer.BytePool.Return(buffer, true);
                            DisposeReason = ClientSessionDisposeReason.IndexKeyError;
                            //key不对
                            Dispose();
                            return;
                        }
#if DEV
                        IRQLog.AppLog.Log(this.m_netIndex.ToString() + ",接收2");
#endif
                        m_KCPServer.OnRecvData(this, buffer, 0, size);
                    }
                }
                finally
                {
                    if (UdpLibConfig.UseBytePool)
                    {
                        m_KCPServer.BytePool.Return(buffer, true);
                    }
                }
            }
        }
    }
Esempio n. 14
0
    public void Connect(string host, int port)
    {
        var endpoint = IPAddress.Parse(host);

        mSocket = new Socket(endpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
        mSocket.Connect(endpoint, port);
        mKCP = new KCP((uint)(new Random().Next(1, Int32.MaxValue)), rawSend);
        // normal:  0, 40, 2, 1
        // fast:    0, 30, 2, 1
        // fast2:   1, 20, 2, 1
        // fast3:   1, 10, 2, 1
        mKCP.NoDelay(0, 30, 2, 1);
        mRecvBuffer.Clear();
    }
Esempio n. 15
0
        //======================================================================
        //连接与断开连接相关
        //======================================================================
        public void Active(Socket socket, IPEndPoint remoteEndPoint)
        {
            RemoteEndPoint = (IPEndPoint)remoteEndPoint;

            if (Interlocked.CompareExchange(ref this.m_actived, 1, 0) == 0)
            {
                m_socket = socket;

                LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;

                m_Kcp = new KCP(Id, HandleKcpSend);
                m_Kcp.NoDelay(1, 10, 2, 1);
                m_Kcp.WndSize(128, 128);
            }
        }
Esempio n. 16
0
        public int Encode(byte[] buf, int size)
        {
            if (size < 8)
            {
                return(-1);
            }

            KCP.ikcp_encode32u(buf, 0, (uint)cmd);
            if (cmd == KcpCmd.KCP_CMD_CONNECT_REQ)
            {
                return(4);
            }
            KCP.ikcp_encode32u(buf, 4, conv);
            return(8);
        }
Esempio n. 17
0
    public KCPClient(IMainLoop mainLoop, NetworkScene ns)
    {
        kcp                   = new KCP();
        kcp.outputFunc        = this.SendKCPPacket;
        kcp.closeEventHandler = this.KCPClosed;
        //KCP 逻辑处理是在主线程上执行的

        msgReader           = new MessageReader();
        msgReader.mainLoop  = mainLoop;
        msgReader.msgHandle = HandleMsg;
        ml           = mainLoop;
        networkScene = ns;

        ml.queueInUpdate(Update);
    }
Esempio n. 18
0
    public static bool Connect(int port, int playerId)
    {
        if (Connected)
        {
            return(false);
        }

        Client = new UdpClient(TcpClientProxy.server.Address.ToString(), port);
        Kcp    = new KCP((uint)playerId, SendWrap);
        Kcp.NoDelay(1, 10, 2, 1);
        Kcp.WndSize(128, 128);
        Receive();
        UpdateTime = 0;
        Connected  = true;
        return(true);
    }
Esempio n. 19
0
        public int Decode(byte[] buf, int size)
        {
            uint n = 0;

            KCP.ikcp_decode32u(buf, 0, ref n);
            if (n >= (uint)KcpCmd.KCP_CMD_COUNT)
            {
                return(-1);
            }
            cmd = (KcpCmd)n;
            if (cmd != KcpCmd.KCP_CMD_CONNECT_REQ)
            {
                KCP.ikcp_decode32u(buf, 4, ref conv);
            }
            return(0);
        }
Esempio n. 20
0
    /// <summary>
    /// 发送数据。发送时,默认在头部加上4字节的key
    /// </summary>
    /// <param name="buf"></param>
    public void Send(byte[] buf)
    {
        byte[] newbuf = new byte[buf.Length + 4];
        //把key附上,服务端合法性检测用
        KCP.ikcp_encode32u(newbuf, 0, (uint)m_Key);
        Array.Copy(buf, 0, newbuf, 4, buf.Length);
        m_LastSendTimestamp = UnityEngine.Time.time;
        m_Kcp.Send(newbuf);
        m_NeedUpdateFlag = true;
        var e = Event;

        if (e != null)
        {
            e(UdpClientEvents.Send, buf);
        }
    }
Esempio n. 21
0
    void init_kcp(UInt32 conv)
    {
        mKcp = new KCP(conv, (byte[] buf, int size) =>
        {
            try
            {
                mUdpClient.Send(buf, size);
            }catch(Exception e)
            {
                Debug.LogError(e);
            }
        });

        mKcp.NoDelay(1, 10, 2, 1);
        mKcp.WndSize(128, 128);
    }
Esempio n. 22
0
        private KCPNet() : base()
        {
            mNetTag   = "KCP";
            kcpObject = new KCP(1, HandleKcpSend);
            kcpObject.NoDelay(1, 10, 2, 1);
            kcpObject.WndSize(128, 128);
            sendCallBack = SendAsyncCallback;

            for (int i = 0; i < 60; i++)
            {
                cacheBytesQue.Enqueue(new CacheByteObject()
                {
                    bytes = new byte[cacheByteLen]
                });
            }
        }
Esempio n. 23
0
        private void ProcessRecvQueue()
        {
            while (!RecvQueue.IsEmpty)
            {
                SocketAsyncEventArgs e = null;
                bool isSuccess         = RecvQueue.TryDequeue(out e);
                if (!isSuccess || e == null)
                {
                    continue;
                }
                if (e.BytesTransferred == 0)
                {
                    mSAEPool.PutObject(e);
                    continue;
                }
                //handshake with {0,0,0,0} at the first
                if (Helper.IsHandshakeDataRight(e.Buffer, e.Offset, e.BytesTransferred))
                {
                    uint conv       = Helper.iclock();
                    var  newSession = new KCPClientSession(conv);
                    newSession.ClientEndPoint  = e.RemoteEndPoint;
                    newSession.KCPOutput       = SendWithSession;
                    newSession.RecvDataHandler = RecvDataHandler;
                    mSessions.TryAdd(conv, newSession);

                    KCP.ikcp_encode32u(e.Buffer, e.BytesTransferred, conv);
                    e.SetBuffer(0, e.BytesTransferred + 4);
                    if (!mServerSocket.SendToAsync(e))
                    {
                        ProcessSend(e);
                    }
                    Console.WriteLine("Handshake from:" + e.RemoteEndPoint.ToString());
                }
                else
                {
                    uint conv = 0;
                    KCP.ikcp_decode32u(e.Buffer, e.Offset, ref conv);
                    KCPClientSession session = null;
                    mSessions.TryGetValue(conv, out session);
                    if (session != null)
                    {
                        session.processRecvQueue(e);
                    }
                    mSAEPool.PutObject(e);
                }
            }
        }
Esempio n. 24
0
 private void createSocket(int conv, string host, int port)
 {
     _remoteEP = new IPEndPoint(IPAddress.Parse(host), port);
     _listenEP = new IPEndPoint(IPAddress.Any, port);
     // 主要一定要设置port为0,不然无法接收到服务器的消息
     _socket = new UdpClient(0);
     _socket.Connect(_remoteEP);
     _kcp = new KCP((uint)conv, (byte[] buf, int size) =>
     {
         //Log4U.LogDebug("ASynKcpUdpClientSocket:createSocket Message send data=", Encoding.ASCII.GetString(buf, 0, size));
         _socket.Send(buf, size);
     });
     // fast mode.
     _kcp.NoDelay(1, 10, 2, 1);
     _kcp.WndSize(128, 128);
     _socket.BeginReceive(ReceiveAsyn, this);
 }
Esempio n. 25
0
        // This method is invoked when an asynchronous receive operation completes.
        // If the remote host closed the connection, then the socket is closed.
        // If data was received then the data is echoed back to the client.
        //
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            try
            {
                Log.Error("EEE=" + e.BytesTransferred + "," + e.SocketError + "," + e.Count);

                if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                {
                    MySocketEventArgs eventArgs = this.receiveEventArgsPool.Rent <MySocketEventArgs>();
                    this.clientSocket.ReceiveFromAsync(eventArgs);

                    //读取数据
                    byte[] data = new byte[e.BytesTransferred];
                    Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);

                    if (!(data.Length < KCP.IKCP_OVERHEAD))
                    {
                        lock (kcpManager)
                        {
                            uint new_conv = 0;
                            KCP.ikcp_decode32u(data, 0, ref new_conv);

                            if (kcpManager.ContainsKey(new_conv))
                            {
                                kcpManager[new_conv].Input(data);
                            }
                        }
                    }

                    this.receiveEventArgsPool.Return((MySocketEventArgs)e);

                    /*
                     * if (!token.ReceiveFromAsync(e))
                     *  this.ProcessReceive(e);
                     */
                }
                else
                {
                    ProcessError(e);
                }
            }
            catch (Exception xe)
            {
                Console.WriteLine(xe.Message);
            }
        }
Esempio n. 26
0
        public void Initialize(object user, KCPSetting setting)
        {
            _kcp = new KCP(setting.conv, user);
            _kcp.SetOutput(OutputKCP);

            // fast mode
            _kcp.NoDelay(setting.nodelay,
                         setting.interval,
                         setting.resend,
                         setting.nc);

            _kcp.WndSize(setting.sndwnd,
                         setting.rcvwnd);

            _recvTimeoutSec = setting.timeoutSec;
            kcpRcvBuf       = new byte[(KCP.IKCP_MTU_DEF + KCP.IKCP_OVERHEAD) * 3];
        }
Esempio n. 27
0
 public void Connect(string ip, int port)
 {
     Debuger.Log("连接服务端 IP {0} Port {1} ", ip, port);
     IP            = ip;
     remoteIp      = ip;
     remotePort    = port;
     remotEndPoint = IPUtility.GetHostEndPoint(ip, port);
     currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     currentSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
     kcp = new KCP(0, HandleKcpSend);
     kcp.NoDelay(1, 10, 2, 1);
     kcp.WndSize(128, 128);
     Connected  = true;
     threadRecv = new Thread(ThreadRecv)
     {
         IsBackground = true
     };
     threadRecv.Start();
 }
Esempio n. 28
0
        /// <summary>
        /// 接收消息线程
        /// </summary>
        private void OnRecive(IAsyncResult ar)
        {
            try
            {
                remoteEndPoint = null;
                byte[] buf = client.EndReceive(ar, ref remoteEndPoint);

                //如果缓冲区为null 或 长度少于等于0,则断线
                if (buf == null || buf.Length <= 0)
                {
                    Dispose();
                    Debug.LogError("kcp buff is None");
                    return;
                }

                //获取会话conv
                UInt32 conv = 0;
                KCP.ikcp_decode32u(buf, 0, ref conv);

                //查找信道池,没有则建立新的

                KChannel channel;
                if (!channels.TryGetValue(conv, out channel))
                {
                    channel = new KChannel(conv, client, remoteEndPoint)
                    {
                        OnRecive = OnRecive
                    };
                    channel.OnConnectState = OnConnectState;
                    channels.Add(conv, channel);
                }

                channel.Input(buf);

                //再次调用异步接收
                client.BeginReceive(OnRecive, null);
            }
            catch (Exception)
            {
                //TODO 触发此处异常,一般由于客户端主动关闭致使S端无法返回数据包到C端。
                //TODO 服务器在此类异常中不需要关闭,只需要处理掉断开连接的C端
            }
        }
Esempio n. 29
0
        public KcpChannel(int port, Action <byte[]> reveiveHandler)
        {
            _recEndPoint = new IPEndPoint(IPAddress.Any, 0);

            _reveiveHandler = reveiveHandler;

            _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));
            _kcp       = new KCP((UInt32) new Random((int)DateTime.Now.Ticks).Next(1, Int32.MaxValue),
                                 UdpSendData);

            //kcp fast mode.
            _kcp.NoDelay(1, 10, 2, 1);
            _kcp.WndSize(128, 128);

            _receiveMeesages = new Queue <byte[]>();

            _udpClient.BeginReceive(UdpReceiveMessage, this);

            new Task(Update).Start();
        }
Esempio n. 30
0
    /// <summary>
    /// 是否是正确的握手响应
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="offset"></param>
    /// <param name="size"></param>
    /// <param name="index"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    internal static bool IsHandshakeDataRight(byte[] buffer, int offset, int size, out uint index, out uint key)
    {
        index = 0;
        key   = 0;
        if (size < UdpLibConfig.HandshakeDataSize)
        {
            return(false);
        }
        for (int i = 0; i < UdpLibConfig.HandshakeHeadData.Length; i++)
        {
            if (buffer[offset + i] != UdpLibConfig.HandshakeHeadData[i])
            {
                return(false);
            }
        }

        KCP.ikcp_decode32u(buffer, offset + UdpLibConfig.HandshakeHeadData.Length, ref index);
        KCP.ikcp_decode32u(buffer, offset + UdpLibConfig.HandshakeHeadData.Length + 4, ref key);
        return(true);
    }
Esempio n. 31
0
 public void Close()
 {
     Connected = false;
     kcp?.Dispose();
     kcp = null;
     threadRecv?.Interrupt();
     threadRecv = null;
     if (currentSocket != null)
     {
         try
         {
             currentSocket.Shutdown(SocketShutdown.Both);
         }
         catch (Exception e)
         {
             Debuger.LogWarning(e.Message + e.StackTrace);
         }
         currentSocket.Close();
         currentSocket = null;
     }
 }
Esempio n. 32
0
        void init_kcp(UInt32 conv)
        {
            mKcp = new KCP(conv, (byte[] buf, int size) =>
            {
                mUdpClient.Send(buf, size);
            });

            mKcp.NoDelay(1, 10, 2, 1);
        }
Esempio n. 33
0
        void reset_state()
        {
            mNeedUpdateFlag = false;
            mNextUpdateTime = 0;

            mInConnectStage = false;
            mConnectSucceed = false;
            mConnectStartTime = 0;
            mLastSendConnectTime = 0;
            mRecvQueue.Clear();
            mKcp = null;
        }