Beispiel #1
0
    private void CleanAndStopNetwork(int errorCore = -1, long _timeDelay = 0)
    {
        if (errorCore != -1)
        {
            if (currentIPDetail != null)
            {
                currentIPDetail.beingError = true;
                currentIPDetail.countConnectionError++;
            }
            if (onNetworkError != null)
            {
                onNetworkError(errorCore);
            }
        }
        else
        {
            if (currentIPDetail != null)
            {
                currentIPDetail.beingError = false;
                currentIPDetail.timeDelay  = _timeDelay;
            }
        }
        if (networkStream != null)
        {
            networkStream.Close();
        }
        if (tcpClient != null)
        {
            tcpClient.Close();
        }

        listIpConnect   = null;
        currentIPDetail = null;
    }
        public async Task <IpDetail> UpdateCacheAsync(IpDetail ip)
        {
            // with the sliding expiration the key will expire if noone access it, but if someone does access it then it will stay for another minute in memory
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetSlidingExpiration(TimeSpan.FromSeconds(60));

            try
            {
                await GetSemaphore.WaitAsync();

                var ipd = CheckCacheForIp(ip.Ip); // Recheck to make sure it didn't populate before entering semaphore
                if (ipd != null)
                {
                    return(ipd);
                }

                MemoryCache.Set(ip.Ip, ip, cacheEntryOptions);
            }
            finally
            {
                GetSemaphore.Release();
            }

            return(ip);
        }
Beispiel #3
0
    void SetListIpForOneHitDefaultData()
    {
        listIpForOneHit = new List <IpDetail>();
        IpDetail _tmpIpDetail = null;

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -1;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv4;
        _tmpIpDetail.ip          = "subv4.bigxuonline.com";
        _tmpIpDetail.port_onehit = 2598;
        listIpForOneHit.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -2;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv6;
        _tmpIpDetail.ip          = "subv6.bigxuonline.com";
        _tmpIpDetail.port_onehit = 2598;
        listIpForOneHit.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -3;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv4;
        _tmpIpDetail.ip          = "subv4.battleoflegend.com";
        _tmpIpDetail.port_onehit = 2598;
        listIpForOneHit.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -4;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv6;
        _tmpIpDetail.ip          = "subv6.battleoflegend.com";
        _tmpIpDetail.port_onehit = 2598;
        listIpForOneHit.Add(_tmpIpDetail);
    }
        public async Task <IpDetail> CheckLibraryForIPAsync(string ip)
        {
            return(await Task.Run(() =>
            {
                var ipd = IpInfoProvider.GetDetails(ip);
                if (ipd != null)
                {
                    var ipDetail = new IpDetail
                    {
                        Ip = ip,
                        City = ipd.City,
                        Country = ipd.Country,
                        Continent = ipd.Continent,
                        Latitude = (decimal?)ipd.Latitude,
                        Longitude = (decimal?)ipd.Longitude
                    };

                    return ipDetail;
                }
                else
                {
                    return null;
                }
            }));
        }
Beispiel #5
0
 public void GetIp()
 {
     try
     {
         string CheckIps = CheckIp();
         if (CheckIps != null && CheckIps.Length > 0)
         {
             string sip = Session["ip"] == null ? null : Session["ip"].ToString();
             if (sip != CheckIps)
             {
                 string   kIP        = Page.Request.UserHostAddress;
                 string   os         = CheckIP.GetOSVersion();
                 string   Brorser    = CheckIP.GetBrowser();
                 IpDetail ipDetail   = IpHelper.Get(CheckIps, null);
                 String   Country    = ipDetail.Country;
                 String   Province   = ipDetail.Province;
                 String   City       = ipDetail.City;
                 String   District   = ipDetail.District;
                 String   Type       = ipDetail.Type;
                 String   Desc       = ipDetail.Desc;
                 string   CREATEDATE = DateTime.Now.ToString();
                 string   remark     = CheckIP.Get();
                 string   sql        = "insert into IPOPERATION(Country, Province, City, District,IsMobileDevice, kIP, os, Brorser, ip,remark,CREATEDATE) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')";
                 sql = string.Format(sql, Country, Province, City, District, IsMobileDevice, kIP, os, Brorser, CheckIps, remark, CREATEDATE);
                 DBHelper.ExecuteCommand(sql);
                 Session["ip"] = CheckIps;
             }
         }
     }
     catch (Exception saa)
     {
         Tool.WritrErro(saa);
     }
 }
Beispiel #6
0
    public SubServerDetail(MessageReceiving _mess)
    {
        listIpDetail   = new List <IpDetail>();
        listRoomDetail = new List <RoomDetail>();

        subServerId   = _mess.readInt();
        version       = _mess.readLong();
        subServerName = _mess.readString();
        countryCode   = _mess.readString();

        short      _numberRoomDetail = _mess.readShort();
        RoomDetail _tmpNewRoomDetail = null;

        for (int i = 0; i < _numberRoomDetail; i++)
        {
            _tmpNewRoomDetail = new RoomDetail(_mess);
            listRoomDetail.Add(_tmpNewRoomDetail);
        }

        short    _numberIpDetail = _mess.readShort();
        IpDetail _tmpIpDetail    = null;

        for (int i = 0; i < _numberIpDetail; i++)
        {
            _tmpIpDetail = new IpDetail(_mess);
            listIpDetail.Add(_tmpIpDetail);
        }
    }
Beispiel #7
0
 public bool IsEqual(IpDetail _other)
 {
     if (ipId == _other.ipId)
     {
         return(true);
     }
     return(false);
 }
Beispiel #8
0
 public void AddNewIpDetail(IpDetail ipDetail)
 {
     using (var context = new AppContext())
     {
         context.Entry(ipDetail).State = EntityState.Added;
         context.SaveChanges();
     }
 }
Beispiel #9
0
 public void EditIpDetail(IpDetail ipDetail)
 {
     using (var context = new AppContext())
     {
         context.Entry(ipDetail).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Beispiel #10
0
    public void LoadListIpForOneHitDataFromSv(List <IpDetail> _newListIpDetail)
    {
        if (_newListIpDetail == null || _newListIpDetail.Count == 0)
        {
            #if TEST
            Debug.LogError(">>> _newListIpDetail is null or count = 0");
            #endif
            return;
        }

        // --- Merge dữ liệu mới và cũ --- //
        for (int i = 0; i < _newListIpDetail.Count; i++)
        {
            for (int j = 0; j < listIpForOneHit.Count; j++)
            {
                if (listIpForOneHit[j].IsEqual(_newListIpDetail[i]))
                {
                    _newListIpDetail[i].InitDataAgain(listIpForOneHit[j]);
                    break;
                }
            }
        }

        IpDetail _tmpIpDetail = new IpDetail();
        _tmpIpDetail.ipId        = -1;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv4;
        _tmpIpDetail.ip          = "subv4.bigxuonline.com";
        _tmpIpDetail.port_onehit = 2598;
        _tmpIpDetail.beingError  = true;
        _newListIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -2;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv6;
        _tmpIpDetail.ip          = "subv6.bigxuonline.com";
        _tmpIpDetail.port_onehit = 2598;
        _tmpIpDetail.beingError  = true;
        _newListIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -3;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv4;
        _tmpIpDetail.ip          = "subv4.battleoflegend.com";
        _tmpIpDetail.port_onehit = 2598;
        _tmpIpDetail.beingError  = true;
        _newListIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail             = new IpDetail();
        _tmpIpDetail.ipId        = -4;
        _tmpIpDetail.ipType      = IpDetail.Type.IPv6;
        _tmpIpDetail.ip          = "subv6.battleoflegend.com";
        _tmpIpDetail.port_onehit = 2598;
        _tmpIpDetail.beingError  = true;
        _newListIpDetail.Add(_tmpIpDetail);

        listIpForOneHit = _newListIpDetail;
    }
Beispiel #11
0
        public void ScanFolder()
        {
            string searchPattern = SearchPattern.Log;
            var    repo          = new DisconnectedRepository();
            var    fileProcessor = new FileProcessor();

            LocalSetting setting        = repo.GetLocalSettings();
            string       folderPath     = @"" + setting.FolderPath;
            var          filesToProcess = fileProcessor.FindNewFiles(folderPath, searchPattern);

            var ipDetails = repo.GetIpDetails();

            List <string> ipNumbers        = ipDetails.Select(p => p.IpNumber).ToList();
            List <string> scannedIpNumbers = new List <string>();


            Guid id = new Guid();

            var logProcessor = new LogProcessor();

            foreach (var logFile in filesToProcess)
            {
                var linesToProcess = logProcessor.FindNewlogLines(logFile);
                var fileInDatabase = repo.GetLogFileByFileName(logFile.FileName);

                if (fileInDatabase != null)
                {
                    id = fileInDatabase.LogFileId;
                }
                else
                {
                    id = logFile.LogFileId;
                    repo.AddNewLogFile(logFile);
                }


                foreach (var logLine in linesToProcess)
                {
                    scannedIpNumbers.Add(logLine.IpClient);

                    logLine.LogFileId = id;

                    repo.AddNewLogLine(logLine);
                }
            }

            var newIpNumbers = scannedIpNumbers.Except(ipNumbers);

            foreach (var item in newIpNumbers)
            {
                var ipDetail = new IpDetail();
                ipDetail.IpNumber = item;
                repo.AddNewIpDetail(ipDetail);
                Console.WriteLine(item);
            }
        }
        /// <summary>
        /// 获取IP地址的详细信息,调用的接口为
        /// http://ip.taobao.com/service/getIpInfo.php?ip={ip}
        /// </summary>
        /// <param name="ipAddress">请求分析得IP地址</param>
        /// <returns>IpUtils.IpDetail</returns>
        public static IpDetail GetIpDetail(string ipAddress)
        {
            var ipDetail = new IpDetail();

            try
            {
                string   ip             = ipAddress;
                Encoding sourceEncoding = Encoding.UTF8;
                using (
                    Stream receiveStream =
                        WebRequest.Create("http://ip.taobao.com/service/getIpInfo.php?ip=" +
                                          ipAddress).
                        GetResponse().GetResponseStream())
                {
                    if (receiveStream != null)
                    {
                        using (var sr = new StreamReader(receiveStream, sourceEncoding))
                        {
                            var readbuffer = new char[256];
                            int n          = sr.Read(readbuffer, 0, readbuffer.Length);
                            int realLen    = 0;
                            while (n > 0)
                            {
                                realLen = n;
                                n       = sr.Read(readbuffer, 0, readbuffer.Length);
                            }
                            ip = ConvertToGb(sourceEncoding.GetString(sourceEncoding.GetBytes(readbuffer, 0, realLen)));
                        }
                    }
                }
                try
                {
                    //ipDetail = Serializer.JsonDeserialize<IpDetail>(ip);IpDetailRes
                    //ipDetail.ip = ipAddress;
                    var entity = Serializer.JsonDeserialize <IpDetailRes>(ip);
                    if (entity.code == "0")
                    {
                        ipDetail          = entity.data;
                        ipDetail.province = entity.data.region;
                    }
                }
                catch
                {
                    //ipDetail.city = "未知";
                }
            }
            catch (Exception ex)
            {
                //ipDetail.city = "未知";
            }
            return(ipDetail);
        }
Beispiel #13
0
    void SetListSubServerDetailDefaultData()
    {
        listSubServerDetail = new List <SubServerDetail>();

        SubServerDetail _subServerDetail = new SubServerDetail();

        _subServerDetail.subServerId   = 0;
        _subServerDetail.subServerName = "Global";
        _subServerDetail.version       = 20181122;
        _subServerDetail.countryCode   = "VN";

        IpDetail _tmpIpDetail = new IpDetail();

        _tmpIpDetail.ipId          = -1;
        _tmpIpDetail.ipType        = IpDetail.Type.IPv4;
        _tmpIpDetail.ip            = "subv4.bigxuonline.com";
        _tmpIpDetail.port_onehit   = 2598;
        _tmpIpDetail.port_realtime = 2589;
        _tmpIpDetail.port_test     = 2704;
        _subServerDetail.listIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail               = new IpDetail();
        _tmpIpDetail.ipId          = -2;
        _tmpIpDetail.ipType        = IpDetail.Type.IPv6;
        _tmpIpDetail.ip            = "subv6.bigxuonline.com";
        _tmpIpDetail.port_onehit   = 2598;
        _tmpIpDetail.port_realtime = 2589;
        _tmpIpDetail.port_test     = 2704;
        _subServerDetail.listIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail               = new IpDetail();
        _tmpIpDetail.ipId          = -3;
        _tmpIpDetail.ipType        = IpDetail.Type.IPv4;
        _tmpIpDetail.ip            = "subv4.battleoflegend.com";
        _tmpIpDetail.port_onehit   = 2598;
        _tmpIpDetail.port_realtime = 2589;
        _tmpIpDetail.port_test     = 2704;
        _subServerDetail.listIpDetail.Add(_tmpIpDetail);

        _tmpIpDetail               = new IpDetail();
        _tmpIpDetail.ipId          = -4;
        _tmpIpDetail.ipType        = IpDetail.Type.IPv6;
        _tmpIpDetail.ip            = "subv6.battleoflegend.com";
        _tmpIpDetail.port_onehit   = 2598;
        _tmpIpDetail.port_realtime = 2589;
        _tmpIpDetail.port_test     = 2704;
        _subServerDetail.listIpDetail.Add(_tmpIpDetail);

        listSubServerDetail.Add(_subServerDetail);
    }
Beispiel #14
0
    void InitListIPForOnehit(MessageReceiving _mess)
    {
        short           _numberServerOnehit       = _mess.readShort();
        List <IpDetail> _newListIpDetailForOnehit = new List <IpDetail>();
        IpDetail        _tmpIpDetail = null;

        for (int i = 0; i < _numberServerOnehit; i++)
        {
            _tmpIpDetail             = new IpDetail();
            _tmpIpDetail.ipId        = _mess.readInt();
            _tmpIpDetail.ip          = _mess.readString();
            _tmpIpDetail.port_onehit = _mess.readInt();
            _newListIpDetailForOnehit.Add(_tmpIpDetail);
        }
        DataManager.instance.subServerData.LoadListIpForOneHitDataFromSv(_newListIpDetailForOnehit);
    }
        public static IpDetail GetIpDetail()
        {
            var model = new IpDetail();

            string ip = GetClientIP();

            if (ip.IsIP())
            {
                var _res = GetIpDetail(ip);
                if (_res != null)
                {
                    model = _res;
                }
            }
            model.ip = ip;
            return(model ?? new IpDetail());
        }
Beispiel #16
0
        public void EditIpDetail(string id, string ipNumber, string ispProvider, string country, string location, string state, bool IsHidden, string alias)
        {
            var      repo   = new DisconnectedRepository();
            IpDetail detail = new IpDetail
            {
                IpNumber    = ipNumber,
                IspProvider = ispProvider,
                Country     = country,
                Location    = location,
                State       = state,
                IpDetailId  = new Guid(id),
                IsHidden    = IsHidden,
                Alias       = alias
            };

            repo.EditIpDetail(detail);
        }
        public IpDetail GetValue(string key)
        {
            var IpDetail = new IpDetail();

            if (!this._providers.TryGetValue(key, out IpDetail))
            {
                var isp = new IpDetail();

                isp.IpNumber    = string.Empty;
                isp.Country     = string.Empty;
                isp.IspProvider = string.Empty;
                isp.Location    = string.Empty;
                isp.State       = string.Empty;
                IpDetail        = isp;
            }

            return(IpDetail);
        }
Beispiel #18
0
 public void CreateNewIsp(IpDetail isp)
 {
     _context.IpDetails.Add(isp);
 }
Beispiel #19
0
        public async Task <int> AddIpDetailsAsync(IpDetail ipDetail)
        {
            Context.Ipdetails.Add(ipDetail);

            return(await Context.SaveChangesAsync());
        }
Beispiel #20
0
    private IEnumerator runNetwork()
    {
        timeStart     = currentTimeMillis;
        tcpClient     = null;
        networkStream = null;
        int numberIpConnect = listIpConnect.Count;

        for (int i = 0; i < numberIpConnect; i++)
        {
            currentIPDetail = listIpConnect[i];
            if (networkStream != null)
            {
                networkStream.Close();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            if (currentIPDetail.ipType == IpDetail.Type.IPv6)
            {
                tcpClient = new TcpClient(AddressFamily.InterNetworkV6);
            }
            else
            {
                tcpClient = new TcpClient();
            }
            // Debug.Log(">>> " + currentIP + ":" + currentPort);

            try {
                //tcpClient.ConnectAsync(currentIPDetail.ip, currentIPDetail.port_realtime);
                tcpClient.BeginConnect(currentIPDetail.ip, currentIPDetail.port_realtime, null, null);
            } catch (Exception s) {
                currentIPDetail.beingError = true;
                currentIPDetail.countConnectionError++;
                currentIPDetail = null;
                tcpClient.Close();
                continue;
            }
            timeStop = currentTimeMillis + 1258;
            while (currentTimeMillis < timeStop)
            {
                if (tcpClient.Connected)
                {
                    break;
                }
                else
                {
                    yield return(Yielders.Get(TIME_SLEEP));
                }
            }
            if (tcpClient.Connected)
            {
                networkStream = tcpClient.GetStream();
                break;
            }
            else
            {
                currentIPDetail.beingError = true;
                currentIPDetail.countConnectionError++;
                currentIPDetail = null;
                tcpClient.Close();
            }
            // try {
            //     if (tcpClient.ConnectAsync(currentIPDetail.ip, currentIPDetail.port_realtime).Wait(258)) {
            //         networkStream = tcpClient.GetStream();
            //         break;
            //     } else {
            //         #if TEST
            //         Debug.Log("Lỗi tạo kết nối đến server: " + currentIPDetail.ip + ":" + currentIPDetail.port_realtime);
            //         #endif
            //         currentIPDetail = null;
            //     }
            // } catch (Exception s) {
            //     #if TEST
            //     Debug.Log("Lỗi tạo kết nối đến server: " + currentIPDetail.ip + ":" + currentIPDetail.port_realtime);
            //     #endif
            //     currentIPDetail = null;
            // }
        }

        if (currentIPDetail == null)
        {
            if (onNetworkError != null)
            {
                onNetworkError(1);
            }
            if (onDisconnect != null)
            {
                onDisconnect();
            }
            yield break;
        }

        timeStop = currentTimeMillis + 1268;
        while (currentTimeMillis < timeStop)
        {
            if (tcpClient.Available < 8)
            {
                yield return(Yielders.Get(TIME_SLEEP));
            }
            else
            {
                break;
            }
        }

        isRelease = false;
        if (currentTimeMillis >= timeStop)
        {
            monoBehaviour.StartCoroutine(release()); if (onNetworkError != null)
            {
                onNetworkError(2);
            }
            yield break;
        }                                                                                                                                          //Rớt mạng thì đóng kết nối

        byte[] temp = new byte[8];
        try { networkStream.Read(temp, 0, temp.Length); } catch (Exception s) { monoBehaviour.StartCoroutine(release()); if (onNetworkError != null)
                                                                                {
                                                                                    onNetworkError(3);
                                                                                }
                                                                                yield break; /*Lỗi bị server đóng kết nối*/ }

        validateCode    = temp[4];
        validateData    = new byte[7];
        validateData[0] = (byte)(temp[0] ^ validateCode);
        validateData[1] = (byte)(temp[1] ^ validateCode);
        validateData[2] = (byte)(temp[2] ^ validateCode);
        validateData[3] = (byte)(temp[3] ^ validateCode);
        validateData[4] = (byte)(temp[5] ^ validateCode);
        validateData[5] = (byte)(temp[6] ^ validateCode);
        validateData[6] = (byte)(temp[7] ^ validateCode);


        sessionId = -1;
        byte[] dataHeader = new byte[9];
        for (int i = 0; i < 7; i++)
        {
            dataHeader[i] = validateData[i];
        }
        dataHeader[7] = (byte)((int)((uint)sessionId >> 8) & 0xFF);
        dataHeader[8] = (byte)((int)((uint)sessionId >> 0) & 0xFF);


        try { networkStream.Write(dataHeader, 0, dataHeader.Length); } catch (Exception s) { monoBehaviour.StartCoroutine(release()); if (onNetworkError != null)
                                                                                             {
                                                                                                 onNetworkError(4);
                                                                                             }
                                                                                             yield break; /*Lỗi mạng*/ }

        while (currentTimeMillis < timeStop)
        {
            if (tcpClient.Available < 2)
            {
                yield return(Yielders.Get(TIME_SLEEP));
            }
            else
            {
                break;                                                                                                      /*Chờ lấy sessionId*/
            }
        }
        if (currentTimeMillis >= timeStop)
        {
            monoBehaviour.StartCoroutine(release()); if (onNetworkError != null)
            {
                onNetworkError(5);
            }
            yield break;                                                                                                                         /*Bị server chặn hack handshark hoặc lỗi mạng*/
        }

        temp = new byte[2];
        try { networkStream.Read(temp, 0, temp.Length); } catch (Exception s) { monoBehaviour.StartCoroutine(release()); if (onNetworkError != null)
                                                                                {
                                                                                    onNetworkError(6);
                                                                                }
                                                                                yield break; /*Lỗi bị server đóng kết nối*/ }

        int t1 = temp[0];
        int t2 = temp[1];
        sessionId = (short)((t1 << 8) + (t2 << 0));//SessionId chỉ được gán ở đây
        if (sessionId == -1)
        {
            if (onServerFull != null)
            {
                onServerFull();
            }
            monoBehaviour.StartCoroutine(release());
        }
        else if (onConnectSuccess != null)
        {
            onConnectSuccess();
        }

        /*
         * Main loop
         *
         */


        int t3, t4;
        int dataLength;
        byte[] dataReceive;
        isRunning         = true;
        nextTimePing      = currentTimeMillis + TIME_PING;
        nextTimeReconnect = currentTimeMillis + TIME_RECONNECT;
        timeStop          = currentTimeMillis + TIME_OUT;
        byte[] ping = new byte[] { 0, 0, 0, 1 };

        while (currentTimeMillis < timeStop && isRunning)
        {
            /*Xử lý những gói tin ngừng xử lý*/
            if (isProcessReceive && listWait != null)
            {
                for (int kkk = 0; kkk < listWait.Count; kkk++)
                {
                    onReceive(listWait[kkk].data); if (timeDelayListWait > 0)
                    {
                        yield return(Yielders.Get(timeDelayListWait));
                    }
                }
                listWait = null;
            }

            if (tcpClient.Available > 8)
            {
                temp = new byte[4];
                networkStream.Read(temp, 0, 4);
                t1         = temp[0];
                t2         = temp[1];
                t3         = temp[2];
                t4         = temp[3];
                dataLength = (t1 << 24) + (t2 << 16) + (t3 << 8) + (t4 << 0);

                networkStream.Read(temp, 0, 4);
                dataServer = temp;                       /*Tránh trường hợp bất đồng bộ*/

                if (dataLength < 2 || 8192 < dataLength) //Trường hợp lỗi
                {
                    actionReconnect();
                    yield return(Yielders.Get(TIME_SLEEP));

                    continue;
                }
                else
                {
                    dataReceive = new byte[dataLength];
                    while (currentTimeMillis < timeStop && isRunning)
                    {
                        if (tcpClient.Available < dataLength)
                        {
                            yield return(Yielders.Get(TIME_SLEEP));
                        }
                        else
                        {
                            break;
                        }
                    }

                    try { networkStream.Read(dataReceive, 0, dataReceive.Length); } catch (Exception eee) { actionReconnect(); continue; }
                    for (int i = 0; i < dataLength; i++)
                    {
                        dataReceive[i] = (byte)(dataReceive[i] ^ validateCode);
                    }

                    if (isProcessReceive && listWait == null)
                    {
                        onReceive(dataReceive);
                    }
                    else
                    {
                        listWait.Add(new byteArrayTemp(dataReceive));
                    }
                }
            }
            else
            {
                yield return(Yielders.Get(TIME_SLEEP));
            }

            if (currentTimeMillis > nextTimePing)
            {
                sendThread(ping);
            }
        }
        monoBehaviour.StartCoroutine(release());
        yield break;
    }
Beispiel #21
0
    public IEnumerator runNetwork()
    {
        timeStart     = currentTimeMillis;
        tcpClient     = null;
        networkStream = null;
        long timeOut;

        int numberIpConnect = listIpConnect.Count;

        for (int i = 0; i < numberIpConnect; i++)
        {
            currentIPDetail = listIpConnect[i];
            if (networkStream != null)
            {
                networkStream.Close();
            }
            if (tcpClient != null)
            {
                tcpClient.Close();
            }
            if (currentIPDetail.ipType == IpDetail.Type.IPv6)
            {
                tcpClient = new TcpClient(AddressFamily.InterNetworkV6);
            }
            else
            {
                tcpClient = new TcpClient();
            }
            // Debug.Log(">>> " + currentIP + ":" + currentPort);

            try {
                //tcpClient.ConnectAsync(currentIPDetail.ip, currentIPDetail.port_onehit);
                tcpClient.BeginConnect(currentIPDetail.ip, currentIPDetail.port_onehit, null, null);
            } catch (Exception s) {
                currentIPDetail.beingError = true;
                currentIPDetail.countConnectionError++;
                currentIPDetail = null;
                tcpClient.Close();
                continue;
            }
            timeOut = currentTimeMillis + 1258;
            while (currentTimeMillis < timeOut)
            {
                if (tcpClient.Connected)
                {
                    break;
                }
                else
                {
                    yield return(Yielders.Get(TIME_SLEEP));
                }
            }
            if (tcpClient.Connected)
            {
                networkStream = tcpClient.GetStream();
                break;
            }
            else
            {
                currentIPDetail.beingError = true;
                currentIPDetail.countConnectionError++;
                currentIPDetail = null;
                tcpClient.Close();
            }
        }
        if (currentIPDetail == null)
        {
            #if TEST
            Debug.LogError("Lỗi tạo kết nối đến server " + serverName);
            for (int i = 0; i < numberIpConnect; i++)
            {
                Debug.LogError("---->" + listIpConnect[i].ip + ":" + listIpConnect[i].port_onehit);
            }
            #endif
            CleanAndStopNetwork(1);
            yield break;
        }

        long _startTime = currentTimeMillis;

        timeOut = currentTimeMillis + TIME_OUT;
        while (currentTimeMillis < timeOut)
        {
            if (tcpClient.Available < 8)
            {
                yield return(Yielders.Get(TIME_SLEEP));
            }
            else
            {
                break;
            }
        }

        if (currentTimeMillis > timeOut)  //Lỗi mạng : kết nối được nhưng lỗi tín hiệu
        {
            CleanAndStopNetwork(10);
            yield break;
        }


        byte[] validateData = new byte[8];
        networkStream.Read(validateData, 0, validateData.Length);
        byte validateCode = validateData[2];

        byte[] dataMessage = messageSending.getBytesArray();
        byte[] dataSending = new byte[dataMessage.Length + 7 + 4];
        dataSending[0] = (byte)(validateData[0] ^ validateCode);
        dataSending[1] = (byte)(validateData[1] ^ validateCode);
        dataSending[2] = (byte)(validateData[3] ^ validateCode);
        dataSending[3] = (byte)(validateData[4] ^ validateCode);
        dataSending[4] = (byte)(validateData[5] ^ validateCode);
        dataSending[5] = (byte)(validateData[6] ^ validateCode);
        dataSending[6] = (byte)(validateData[7] ^ validateCode);
        int lengthData = dataMessage.Length;
        int l          = lengthData;
        dataSending[7]  = (byte)(l >> 24);
        dataSending[8]  = (byte)(l >> 16);
        dataSending[9]  = (byte)(l >> 8);
        dataSending[10] = (byte)l;
        for (int i = 0; i < lengthData; i++)
        {
            dataSending[i + 11] = (byte)(dataMessage[i] ^ validateCode);
        }

        /*Nếu dữ liệu trên 8k cần code lại chỗ này*/
        if (dataSending.Length > BUFFER_SENDING)
        {
            Debug.LogError("ERROR ONEHIT : cần code lại phần send dữ liệu quá 8k"); yield break;
        }
        try {
            networkStream.Write(dataSending, 0, dataSending.Length);
            timeOut = currentTimeMillis + TIME_OUT;
        } catch (IOException e) {
            CleanAndStopNetwork(11);
            yield break;
        }

        /*Nếu không setup hàm nhận thì đóng kết nối luôn*/
        if (onReceiveMessage == null)
        {
            yield return(new WaitForSeconds(5)); networkStream.Close(); tcpClient.Close(); yield break;
        }

        while (currentTimeMillis < timeOut)
        {
            if (tcpClient.Available > 4)
            {
                break;
            }
            else
            {
                yield return(Yielders.Get(TIME_SLEEP));
            }
        }


        if (currentTimeMillis >= timeOut)  //Gởi data không hợp lệ bị server ngắt kết nối và không trả về gì
        {
#if TEST
            Debug.LogError("Lỗi gởi sai dữ liệu Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
#endif
            CleanAndStopNetwork(12);
            yield break;
        }

        timeOut = currentTimeMillis + 8952;
        byte[] dataReceive = new byte[4];
        networkStream.Read(dataReceive, 0, dataReceive.Length);

        int lengthDataReceive = (dataReceive[0] << 24) + (dataReceive[1] << 16) + (dataReceive[2] << 8) + (dataReceive[3] << 0);
        dataReceive = new byte[lengthDataReceive];

        if (lengthDataReceive + 4 <= BUFFER_SENDING)
        {
            while (currentTimeMillis < timeOut)
            {
                if (tcpClient.Available < lengthDataReceive)
                {
                    yield return(Yielders.Get(TIME_SLEEP));
                }
                else
                {
                    break;
                }
            }
            if (currentTimeMillis >= timeOut || tcpClient.Available < lengthDataReceive)  //Gởi data không hợp lệ bị server ngắt kết nối và không trả về gì
            {
#if TEST
                Debug.LogError("Lỗi network nhận Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
#endif
                CleanAndStopNetwork(13);
                yield break;
            }
            else
            {
                networkStream.Read(dataReceive, 0, lengthDataReceive);
            }
        }
        else
        {
            while (currentTimeMillis < timeOut)
            {
                if (tcpClient.Available < BUFFER_SENDING - 4)
                {
                    yield return(Yielders.Get(TIME_SLEEP));
                }
                else
                {
                    break;
                }
            }
            networkStream.Read(dataReceive, 0, BUFFER_SENDING - 4);
            networkStream.WriteByte(1);
            int count = BUFFER_SENDING - 4;
            while (count < lengthDataReceive && currentTimeMillis < timeOut)
            {
                if (count + BUFFER_SENDING < lengthDataReceive)
                {
                    if (tcpClient.Available >= BUFFER_SENDING)
                    {
                        networkStream.Read(dataReceive, count, BUFFER_SENDING);
                        count   = count + BUFFER_SENDING;
                        timeOut = currentTimeMillis + TIME_OUT;
                        networkStream.WriteByte(1);//Nhận được là gởi 1 đi
                    }
                    else
                    {
                        yield return(Yielders.Get(TIME_SLEEP));
                    }
                }
                else
                {
                    if (tcpClient.Available >= lengthDataReceive - count)
                    {
                        networkStream.Read(dataReceive, count, lengthDataReceive - count);
                        networkStream.WriteByte(1);
                        count = lengthDataReceive;
                        break;
                    }
                    else
                    {
                        yield return(Yielders.Get(TIME_SLEEP));
                    }
                }
            }
            if (count < lengthDataReceive || currentTimeMillis >= timeOut)
            {
#if TEST
                Debug.LogError("Lỗi network nhận Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
#endif
                CleanAndStopNetwork(14);
                yield break;
            }
        }

        for (int i = 0; i < dataReceive.Length; i++)
        {
            dataReceive[i] = (byte)(dataReceive[i] ^ validateCode);
        }
        MessageReceiving messageReceiving = new MessageReceiving(dataReceive);
        if (messageReceiving.getCMD() == -7 || messageReceiving.getCMD() == -17)
        {
#if TEST
            if (messageReceiving.getCMD() == -7)
            {
                Debug.LogError("Lỗi network không tìm được CMD Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
            }
            else
            {
                Debug.LogError("Lỗi Foward CMD Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
            }
#endif
            CleanAndStopNetwork(15);
            yield break;
        }
        else
        {
            onReceiveMessage(messageReceiving);
#if TEST
            if (messageReceiving.avaiable() > 0)
            {
                Debug.LogError("Lỗi chưa đọc hết CMD Onehit(" + currentIPDetail.ip + ":" + currentIPDetail.port_onehit + ")➡ " + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " " + messageSending.getBytesArray().Length + " byte");
            }
            else
            {
                Debug.LogWarning(currentIPDetail.ip + ":" + currentIPDetail.port_onehit + "  --->" + CMD_ONEHIT.getCMDName(messageSending.getCMD()) + " Send(" + messageSending.getBytesArray().Length + ")➡Receive(" + messageReceiving.lengthReceive() + ")" + (currentTimeMillis - timeStart) + " Giây");
            }
#endif
        }

        CleanAndStopNetwork(-1, currentTimeMillis - _startTime);
        yield break;
    }
Beispiel #22
0
        public JsonResult CreateHuByIpDetail(string IpDetailidStr, string IpDetailucStr, string IpDetailsupplierLotNoStr, string IpDetailqtyStr, bool IpDetailisExport)
        {
            try
            {
                IList <IpDetail> nonZeroIpDetailList = new List <IpDetail>();
                if (!string.IsNullOrEmpty(IpDetailidStr))
                {
                    string[] idArray            = IpDetailidStr.Split(',');
                    string[] ucArray            = IpDetailucStr.Split(',');
                    string[] supplierLotNoArray = IpDetailsupplierLotNoStr.Split(',');
                    string[] qtyArray           = IpDetailqtyStr.Split(',');
                    IpMaster ipMaster           = null;

                    if (idArray != null && idArray.Count() > 0)
                    {
                        for (int i = 0; i < idArray.Count(); i++)
                        {
                            IpDetail ipDetail = base.genericMgr.FindById <IpDetail>(Convert.ToInt32(idArray[i]));
                            if (ipMaster == null)
                            {
                                ipMaster            = base.genericMgr.FindById <IpMaster>(ipDetail.IpNo);
                                ipMaster.HuTemplate = ipMaster.HuTemplate.Trim();
                            }

                            ipDetail.UnitCount        = Convert.ToDecimal(ucArray[i]);
                            ipDetail.SupplierLotNo    = supplierLotNoArray[i];
                            ipDetail.LotNo            = LotNoHelper.GenerateLotNo();
                            ipDetail.ManufactureParty = ipMaster.PartyFrom;
                            ipDetail.HuQty            = Convert.ToDecimal(qtyArray[i]);
                            nonZeroIpDetailList.Add(ipDetail);
                        }
                    }
                    base.genericMgr.CleanSession();
                    if (string.IsNullOrEmpty(ipMaster.HuTemplate))
                    {
                        ipMaster.HuTemplate = this.systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.DefaultBarCodeTemplate);
                    }


                    if (ipMaster != null)
                    {
                        IList <Hu> huList = huMgr.CreateHu(ipMaster, nonZeroIpDetailList);
                        foreach (var hu in huList)
                        {
                            hu.ManufacturePartyDescription = base.genericMgr.FindById <Party>(hu.ManufactureParty).Name;
                        }

                        if (IpDetailisExport)
                        {
                            IList <PrintHu> printHuList = Mapper.Map <IList <Hu>, IList <PrintHu> >(huList);

                            IList <object> data = new List <object>();
                            data.Add(printHuList);
                            data.Add(CurrentUser.FullName);
                            reportGen.WriteToClient(ipMaster.HuTemplate, data, ipMaster.HuTemplate);
                            return(Json(null));
                        }
                        else
                        {
                            //CreateBarCode(huList, ipMaster.IpNo);
                            string printUrl = PrintHuList(huList, ipMaster.HuTemplate);
                            SaveSuccessMessage("条码打印成功,共打印了{0}张条码", huList.Count.ToString());
                            return(Json(new { PrintUrl = printUrl }));
                        }
                    }
                }
                return(Json(null));
            }
            catch (BusinessException ex)
            {
                SaveBusinessExceptionMessage(ex);
            }
            catch (Exception ex)
            {
                SaveErrorMessage(ex);
            }
            return(Json(null));
        }
Beispiel #23
0
 public void InitDataAgain(IpDetail _other)
 {
     beingError           = _other.beingError;
     countConnectionError = _other.countConnectionError;
     timeDelay            = _other.timeDelay;
 }