Пример #1
0
        private void ConnectInternal()
        {
            try
            {
                //start keepAlive timer only on first connect
                if (_reconnectTimer == null)
                {
                    _reconnectTimer          = new System.Timers.Timer(_settings.ReconnectInterval * 1000);
                    _reconnectTimer.Elapsed += ReconnectTimer_Elapsed;;
                    _reconnectTimer.Start();
                }

                if (_isInConnectInternal)
                {
                    return;
                }
                _isInConnectInternal = true;

                if (_socket != null)
                {
                    try { _socket.Dispose(); } catch { }
                    _socket = null;
                }

                foreach (var serverAddress in _settings.ServerAddressList)
                {
                    try
                    {
                        _socket = TcpSocketsUtils.Connect(serverAddress.Item1, serverAddress.Item2);
                        break;
                    }
                    catch
                    {
                        OnDebugLog?.Invoke(DebugLogType.ConnectFailed, $" host:{serverAddress.Item1} port:{serverAddress.Item2} ");
                    }
                }
                _connectEvent.Set();


                if (_socket != null)
                {
                    IsConnected = true;
                    OnConnect?.Invoke();
                    TcpSocketsUtils.Recv(
                        _socket,
                        OnRecv,
                        OnExcp,
                        OnRecvProgress,
                        _settings.ReceiveBufferSize == 0 ? TcpSocketsUtils.ms_DefualtReceiveBufferSize : _settings.ReceiveBufferSize,
                        true);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _isInConnectInternal = false;
            }
        }
Пример #2
0
        private void OnSend(int dataSentBytes, int grossSentBytes)
        {
            TotalDataBytesSent  += dataSentBytes;
            TotalGrossBytesSent += grossSentBytes;

            OnDebugLog?.Invoke(DebugLogType.OnSend, $"dataSentBytes:{dataSentBytes}, grossSentBytes:{grossSentBytes}, TotalDataBytesSent:{TotalDataBytesSent}, TotalGrossBytesSent:{TotalGrossBytesSent}");
        }
Пример #3
0
        private void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (_isDisposed)
            {
                return;
            }

            var isRecvActive = (DateTime.UtcNow - _lastRecvProgressTime).TotalSeconds < 10 || (DateTime.UtcNow - _lastRecvTime).TotalSeconds < 10;

            if (isRecvActive)
            {
                var recvInProgressBuf = ConnectorsUtils.SerializeRequestPacket(ConnectorsUtils.RequestTypeRecvInProgress, 0, 0, 0, 0);
                TcpSocketsUtils.Send(_socket, recvInProgressBuf, OnSend, OnExcp);
            }


            if ((DateTime.UtcNow - _lastKeepAliveTime).TotalSeconds > _settings.KeepAliveDisconnectInterval)
            {
                if (isRecvActive == false)
                {
                    if (_socket != null && IsConnected)
                    {
                        OnDebugLog?.Invoke(DebugLogType.OnKeepAlive, "Need to Disconnect");
                        IsConnected = false;
                        try { _socket.Dispose(); } catch { }
                        _socket = null;
                        OnDisconnect?.Invoke();
                    }
                }
                else
                {
                    OnDebugLog?.Invoke(DebugLogType.OnKeepAlive, "Need to Disconnect, but RecvProgressTime/RecvTime is in less than 10 seconds");
                }
            }

            if (_socket == null || _socket.Connected == false) //todo: check also keep alive status
            {
                DisconnectInternal();
                if (_settings.AutoReconnect)
                {
                    ConnectInternal();
                }
            }
        }
Пример #4
0
        private void KeepAliveTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _keepAliveTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            foreach (var connector in _contextMap.Values)
            {
                bool needToDisconnect = true;
                //check new context
                if ((DateTime.UtcNow - connector._connectedTime).TotalSeconds < _settings.KeepAliveGraceInterval)
                {
                    needToDisconnect = false;
                }

                //_lastReceivedLeepAliveTimestamp less than 30 seconds, and if ReceivedInProgress give x6 time
                var keepAliveDisconnectInterval = _settings.KeepAliveDisconnectInterval;
                if ((DateTime.UtcNow - connector._lastReceivedInProgressTime).TotalSeconds < 20)
                {
                    keepAliveDisconnectInterval *= 6;
                }

                if ((_keepAliveTimestamp - connector._lastReceivedKeepAliveTimestamp) < keepAliveDisconnectInterval)
                {
                    needToDisconnect = false;
                }


                if (needToDisconnect)
                {
                    OnDebugLog?.Invoke(connector, DebugLogType.OnKeepAlive, "Need to Disconnect");
                    try { connector.Socket.Close(); } catch { }
                    connector.OnExcp(null);
                    continue;
                }

                //send new keep alive
                var keepaliveBuf = ConnectorsUtils.SerializeRequestPacket(ConnectorsUtils.RequestTypeKeepAlive, 0, 0, _keepAliveTimestamp, 0);
                TcpSocketsUtils.Send(connector.Socket, keepaliveBuf, connector.OnSend, connector.OnExcp);
            }
        }
Пример #5
0
 internal void TriggerOnDebugLog(ServerConnectorContext serverConnectorContext, DebugLogType logType, string info)
 {
     OnDebugLog?.Invoke(serverConnectorContext, logType, info);
 }
Пример #6
0
 public void SetDebugMode(bool debug)
 {
     DEBUG_ENABLED = debug;
     onDebugLog += _Controller.DebugLog;
 }
Пример #7
0
        private void OnRecv(byte[] buf, int grossRecvBytes)
        {
            try
            {
                TotalDataBytesReceived  += buf.Length;
                TotalGrossBytesReceived += grossRecvBytes;

                OnDebugLog?.Invoke(DebugLogType.Info, $"OnRecv - start, dataRecvBytes:{buf.Length}, grossRecvBytes:{grossRecvBytes}, TotalDataBytesReceived:{TotalDataBytesReceived}, TotalGrossBytesReceived:{TotalGrossBytesReceived}");

                _lastRecvTime = DateTime.UtcNow;

                // module, command
                if (buf[0] == 0) //request response packet
                {
                    object reqPacket = null;
                    int    requestId = 0;
                    byte   module = 0, command = 0, requestType = 0;
                    try
                    {
                        requestType = buf[1];
                        OnDebugLog?.Invoke(DebugLogType.Info, $"OnRecv - requestType = {requestType}");
                        if (requestType != ConnectorsUtils.RequestTypeRequestMultiResponses)
                        {
                            reqPacket = ConnectorsUtils.DeserializeRequestPacket(buf, _settings.PacketsMap, out requestId, out module, out command);
                        }
                    }
                    catch (Exception ex) { OnDebugLog?.Invoke(DebugLogType.OnRecvException, ex.ToString()); }

                    if (requestType == ConnectorsUtils.RequestTypeKeepAlive) //keep alive
                    {
                        _lastKeepAliveTime = DateTime.UtcNow;
                        TcpSocketsUtils.Send(_socket, buf, OnSend, OnExcp);
                        OnDebugLog?.Invoke(DebugLogType.OnKeepAlive, reqPacket.ToString());
                        return;
                    }

                    if (requestType == ConnectorsUtils.RequestTypeRequestResponse)
                    {
                        if (requestId % 2 == 1)
                        {
                            if (module == 0 && command == 1)
                            {
                                _reqResHandler.HandleExceptionResponse(
                                    requestId,
                                    new Exception("Exception in Server, check inner exception", new Exception((reqPacket ?? "").ToString())));
                            }
                            else
                            {
                                _reqResHandler.HandleResponse(requestId, reqPacket);
                            }
                        }
                        else
                        {
                            if (module == 0 && command == 1)
                            {
                                _reqResAsyncHandler.HandleExceptionResponse(
                                    requestId,
                                    new Exception("Exception in Server, check inner exception", new Exception((reqPacket ?? "").ToString())));
                            }
                            else
                            {
                                _reqResAsyncHandler.HandleResponse(requestId, reqPacket);
                            }
                        }
                    }

                    if (requestType == ConnectorsUtils.RequestTypeRequestMultiResponses)
                    {
                        reqPacket = ConnectorsUtils.DeserializeMultiResponsePacket(
                            buf, _settings.PacketsMap, out requestId,
                            out bool isLast, out int nReceived, out int nTotal,
                            out module, out command);

                        if (module == 0 && command == 1)
                        {
                            _reqMultiResHandler.HandleExceptionResponse(requestId, new Exception((reqPacket ?? "").ToString()));
                        }
                        else
                        {
                            OnDebugLog?.Invoke(DebugLogType.Info, $"OnRecv - ConnectorsUtils.RequestTypeRequestMultiResponses");

                            _reqMultiResHandler.HandleResponse(requestId, reqPacket, isLast, nReceived, nTotal);
                        }
                    }
                }
                else //packet
                {
                    object packet = ConnectorsUtils.DeserializePacket(buf, _settings.PacketsMap, out byte module, out byte command);
                    _packetsQueue.Add(new Tuple <int, int, object>(module, command, packet));
                }
            }
            catch (Exception ex)
            {
                OnDebugLog?.Invoke(DebugLogType.OnRecvException, ex.ToString());
            }
        }
Пример #8
0
 private void OnDebugLog(OnDebugLog obj)
 {
     text.text += obj.message + "\n";
 }