/// <summary> /// 连接制定ip和端口 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> public void Connect(string ip, int port) { m_connectStartTime = TimeUtils.CurLocalTimeMilliSecond(); m_status = SocketStatus.Connecting; m_active = false; m_netReader.Clear(); m_netSender.Clear(); m_canTargetEvent = true; PackageOut.ResetIndex(); lock (this) { sendCout = 0; } try { IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, port); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, SEND_TIME_OUT); m_socket.BeginConnect(ipEndpoint, new AsyncCallback(M_ConnectCallBack), m_socket); } catch (Exception) { Debug.LogError("服务器关闭,请稍后重试"); m_socket.Close(); m_status = SocketStatus.Closed; } }
public void Update() { if (m_socket == null) { if (m_canTargetEvent) { if (null != eventConnectClose) { eventConnectClose(m_channel); } m_canTargetEvent = false; } return; } if (m_status == SocketStatus.Connecting) { if ((TimeUtils.CurLocalTimeMilliSecond() - m_connectStartTime) >= CONNECT_TIME_OUT_TIME) { m_socket.Close(); m_status = SocketStatus.Closed; m_asyncStatus = AsyncStatus.None; if (null != eventConnectTimeOut) { eventConnectTimeOut(m_channel); } } } else if (m_status == SocketStatus.Connected && !m_socket.Connected) { m_status = SocketStatus.Closed; m_asyncStatus = AsyncStatus.None; if (null != eventConnectClose) { eventConnectClose(m_channel); } } else if (m_asyncStatus == AsyncStatus.ConnectFailed) { m_netReader.Clear(); m_netSender.Clear(); m_asyncStatus = AsyncStatus.None; if (null != eventConnectFailed) { eventConnectFailed(m_channel); } } else if (m_asyncStatus == AsyncStatus.ConnectSucceed) { m_asyncStatus = AsyncStatus.None; if (null != eventConnectSucceed) { eventConnectSucceed(m_channel); } } else if (m_asyncStatus == AsyncStatus.SendFailed) { m_socket.Close(); m_status = SocketStatus.Closed; m_asyncStatus = AsyncStatus.None; if (null != eventSendFailed) { eventSendFailed(m_channel); } } while (m_status == SocketStatus.Connected && m_netReader.HasNext()) { m_netReader.HandleNext(); } }
/// <summary> /// 加载版本文件 /// </summary> /// <param name="onComplete"></param> /// <param name="onError"></param> public void LoadVersion(Action onComplete, Action onError) { string url = GameConfig.HOST_RES() + GameConfig.LOCAL_HTTP_CONFIG_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(url), (req, resp) => { if (resp != null) { Loom.RunAsync(() => { m_httpConfig = JsonFx.Json.JsonReader.Deserialize <VersionBundleConfig>(resp.DataAsText); M_CacheHttpBundles(); string infoFilePath = PathUtils.MakeFilePath(GameConfig.LOCAL_DOWNLOAD_INFO_FILE, PathUtils.PathType.MobileDiskWrite); if (File.Exists(infoFilePath)) { using (FileStream infoStream = File.OpenRead(infoFilePath)) { if (infoStream != null) { byte[] index = new byte[infoStream.Length]; infoStream.Read(index, 0, index.Length); string content = System.Text.Encoding.Default.GetString(index); DownloadFileInfo downloadFileInfo = JsonFx.Json.JsonReader.Deserialize <DownloadFileInfo>(content); ResHelper.Instance().lastZipIndex = downloadFileInfo.totalSize; for (int i = 0; i < downloadFileInfo.ids.Length; i++) { ResHelper.Instance().downloadedFiles.Add(downloadFileInfo.ids[i], 1); } } } } if (GameConfig.useLocalRes) { m_version = new VersionConfig(); m_version.version = "0.0.0"; Loom.QueueOnMainThread(() => { if (onComplete != null) { onComplete(); } }); } else { url = GameConfig.HOST_RES_ZIP() + "zip/" + GameConfig.LOCAL_VERSION_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest zipRequest = new BestHTTP.HTTPRequest(new Uri(url), (zipReq, zipResp) => { if (zipResp != null) { m_version = JsonFx.Json.JsonReader.Deserialize <VersionConfig>(zipResp.DataAsText); if (null != onComplete) { onComplete(); } } else { if (null != onError) { onError(); } } }); zipRequest.Send(); } }); } else { if (null != onError) { onError(); } } }); request.DisableCache = true; request.Send(); }
void OnDownloadConfig(string versionValue) { string fileName = versionValue + ".zip"; string url = GameConfig.HOST_RES_ZIP() + "zip/" + fileName + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); string filePath = PathUtils.MakeFilePath(fileName, PathUtils.PathType.MobileDiskWrite); float progress = 0f; //使用流操作文件 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); //获取文件现在的长度 long fileLength = fs.Length; //获取下载文件的总长度 //long totalLength = GetLength(url); HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Timeout = 60000; HttpWebResponse response = request.GetResponse() as HttpWebResponse; long totalLength = response.ContentLength; string size = (totalLength / 1048576f).ToString("0.00") + "MB"; string tips = "下载更新包:0/" + size; DownloadTips dt = new DownloadTips() { tips = tips }; MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0); DateTime startTime = DateTime.Now; //如果没下载完 if (fileLength < totalLength) { //断点续传核心,设置本地文件流的起始位置 fs.Seek(fileLength, SeekOrigin.Begin); //断点续传核心,设置远程访问文件流的起始位置 request.AddRange((int)fileLength); Stream stream = response.GetResponseStream(); byte[] buffer = new byte[1024]; //使用流读取内容到buffer中 //注意方法返回值代表读取的实际长度,并不是buffer有多大,stream就会读进去多少 int length = stream.Read(buffer, 0, buffer.Length); while (length > 0) { //将内容再写入本地文件中 fs.Write(buffer, 0, length); //计算进度 fileLength += length; progress = (float)fileLength / (float)totalLength; dt.tips = "下载更新包:" + (fileLength / 1048576f).ToString("0.00") + "/" + size; dt.progress = progress; dt.speed = "速度:" + (int)(fileLength / 1024f / (DateTime.Now - startTime).TotalSeconds) + "KB/s"; MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0); //类似尾递归 length = stream.Read(buffer, 0, buffer.Length); } stream.Close(); stream.Dispose(); } else { progress = 1; } fs.Close(); fs.Dispose(); //如果下载完毕,执行回调 if (progress == 1) { OnDecompressConfig(versionValue); } }
IEnumerator M_LoadConfig(Action onComplete, Action onError) { string url = GameConfig.HOST_RES() + "ab/" + GameConfig.LOCAL_CONFIG_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); WWW loader = new WWW(url); yield return(loader); if (string.IsNullOrEmpty(loader.error)) { VersionBundleConfig config = JsonFx.Json.JsonReader.Deserialize <VersionBundleConfig>(loader.text); m_loadedConfig = config; M_CacheBundles(); if (onComplete != null) { onComplete(); } } else { JZLog.LogError(loader.error); if (onError != null) { onError(); } } }