Beispiel #1
0
    /*
     * public void OnDisable()
     * {
     *  KService.Instance.Dispose();
     * }*/

    public void OnGUI()
    {
        GUILayout.BeginVertical();
        if (GUILayout.Button("Connect", GUILayout.Width(200)))
        {
            //m_kChannel.Connect();

            m_kChannel = (KChannel)m_KService.ConnectChannel(NetHelper.ToIPEndPoint("127.0.0.1", 2000));
        }
        if (GUILayout.Button("DisConnect", GUILayout.Width(200)))
        {
            m_kChannel.DisConnect();
        }
        if (GUILayout.Button("Send", GUILayout.Width(200)))
        {
            using (var mem = new MemoryStream())
            {
                var word_byts = Encoding.UTF8.GetBytes("Hello Udp!");
                mem.Write(word_byts, 0, word_byts.Length);
                mem.Position = 0;
                m_kChannel.Send(mem);
            }
        }
        GUILayout.EndVertical();
    }
Beispiel #2
0
    public LTTask <ErrorCode> Connect(IPEndPoint remoteEndPoint)
    {
        this.tcs            = new LTTaskCompletionSource <ErrorCode>();
        this.IsConnected    = false;
        this.RemoteEndPoint = remoteEndPoint;
        uint conv = ConvGenerator.Conv();

        Log.Debug($"connect:new conv:{conv}");

        //#if IPV4
        this.udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
        //#elif IPV6
        //        this.udpClient = new UdpClient(new IPEndPoint(IPAddress.IPv6Any, 0));
        //#endif
        this.udpClient.BeginReceive(OnBeginReceive, null);
        this.channel = new KChannel(conv, udpClient, remoteEndPoint)
        {
            Name = "Client"
        };
        this.channel.OnReadCallback  = OnKcpRead;
        this.channel.OnErrorCallback = OnKcpError;

        //立刻发送连接请求
        byte     hid = 1;
        IMessage msg = MessagesFactory.Connect(hid);

        Send(msg.Encode());

        this.monoDriver.StartCoroutine(SimulationRecvConnected());
        return(this.tcs.Task);
    }
Beispiel #3
0
    private void OnKcpError(KChannel channel, ErrorCode error)
    {
        Log.Error($"error code:{error}");

        //兼容旧版本时,不考虑是否可链接成功
        //if (error == ErrorCode.ERR_KcpCantConnect)
        //{
        //    if (tcs.Task.IsCompleted)
        //    {
        //        Log.Error("OnKcpError task is completed.");
        //        return;
        //    }

        //    tcs.SetResult(error);

        //    Shutdown();
        //    OnErrorEventHandler?.Invoke(error);
        //}
        if (error == ErrorCode.ERR_SocketError)
        {
            if (!tcs.Task.IsCompleted)
            {
                tcs.SetResult(error);
            }

            Shutdown();
            OnErrorEventHandler?.Invoke(error);
        }
        else
        {
            //非指定错误,执行重连
            Shutdown();
            Reconnect();
        }
    }
Beispiel #4
0
    /// <summary>
    /// 内部解析
    /// </summary>
    private void OnKcpRead(KChannel channel, byte[] bytes)
    {
        //处理连接
        if (!this.IsConnected)
        {
            //兼容1.3.1旧版本时,改用SimulationRecvConnected
            //OnConnectedSuccess();
        }
        else
        {
            //解析数据
            header.Clear();
            header.Decode(bytes, 0);

            if (header.GetMessageType() != MessageType.Msg)
            {
                int ts = (SystemTime.LowClientNow() - header.TimeStamp) / 2;

                Log.Debug("当前延迟:" + ts);

                if (ts < 0)
                {
                    ts = 10;
                }

                timeStampList.Add((uint)ts);
            }

            OnReadEventHandler?.Invoke(bytes);
        }
    }
Beispiel #5
0
        private void OnServiceReadCallback(KChannel channel, byte[] buf)
        {
            Debug.Log("kcp recv:" + buf.Length);
            var msg = packager.Decode(buf) as MessageKeyboard;

            //数据回传客户端
            channel.Send(buf);

            App.Make <IEventDispatcher>().Dispatch(new GamepadEventArgs(msg));
        }
Beispiel #6
0
    public void Shutdown()
    {
        Log.Debug("Session Shutdown.");

        monoDriver.StopCoroutine(this.coroutineSendHeart);
        monoDriver.StopCoroutine(this.coroutineRefreshPing);

        Disconnect();
        IsConnected = false;
        channel?.Dispose();
        channel = null;

        udpClient?.Dispose();
        udpClient = null;
    }
Beispiel #7
0
 private void OnServiceErrorCallback(KChannel channel, ErrorCode error)
 {
     Debug.Log($"Service channel:{channel.Conv}  error:{error}");
     this.removeChannels.Add(channel);
 }
        private static async ETTask CheckAsync(RouterCheckComponent self)
        {
            Session session    = self.GetParent <Session>();
            long    instanceId = self.InstanceId;

            while (true)
            {
                if (self.InstanceId != instanceId)
                {
                    return;
                }

                await TimerComponent.Instance.WaitAsync(1000);

                if (self.InstanceId != instanceId)
                {
                    return;
                }

                long time = TimeHelper.ClientFrameTime();

                if (time - session.LastRecvTime < 7 * 1000)
                {
                    continue;
                }

                try
                {
                    long     sessionId  = session.Id;
                    uint     localConn  = 0;
                    uint     remoteConn = 0;
                    KService service    = session.AService as KService;
                    KChannel kChannel   = service.Get(sessionId);
                    if (kChannel == null)
                    {
                        Log.Warning($"not found remoteConn: {sessionId}");
                        continue;
                    }

                    localConn  = kChannel.LocalConn;
                    remoteConn = kChannel.RemoteConn;

                    IPEndPoint realAddress = self.GetParent <Session>().RemoteAddress;
                    Log.Info($"get recvLocalConn start: {self.ClientScene().Id} {realAddress} {localConn} {remoteConn}");

                    (uint recvLocalConn, IPEndPoint routerAddress) = await RouterHelper.GetRouterAddress(self.ClientScene(), realAddress, localConn, remoteConn);

                    if (recvLocalConn == 0)
                    {
                        Log.Error($"get recvLocalConn fail: {self.ClientScene().Id} {routerAddress} {realAddress} {localConn} {remoteConn}");
                        continue;
                    }

                    Log.Info($"get recvLocalConn ok: {self.ClientScene().Id} {routerAddress} {realAddress} {recvLocalConn} {localConn} {remoteConn}");

                    session.LastRecvTime = TimeHelper.ClientNow();

                    ((KService)session.AService).ChangeAddress(sessionId, routerAddress);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
        }