Unity FTP協議加載
文件傳輸協議(英文:File Transfer Protocol,縮寫:FTP)是用於在網絡上進行文件傳輸的一套標準協議,使用客戶/服務器模式。它屬於網絡傳輸協議的應用層。文件傳送(file transfer)和文件訪問(file access)之間的區別在於:前者由FTP提供,後者由如NFS等應用系統提供。
FTP是一個8位的客戶端-服務器協議,能操作任何類型的文件而不需要進一步處理,就像MIME或Unicode一樣。但是,FTP有着極高的延時,這意味着,從開始請求到第一次接收需求數據之間的時間,會非常長;並且不時的必須執行一些冗長的登錄進程。
本文章是unity 連接ftp服務器, 可以先下載 FileZilla Server 搭建一個ftp的服務器,詳情可以百度一下.
//創建FTP連接
public FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod)
{
FtpWebRequest request = (FtpWebRequest) FtpWebRequest.Create(uri);
request.Credentials = networkCredential;
request.KeepAlive = true;
request.UseBinary = true;
request.Method = requestMethod;
return request;
}
// 獲取服務器返回的響應體
public FtpWebResponse GetFtpResponse(FtpWebRequest request)
{
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) request.GetResponse();
return response;
}
catch (WebException ex)
{
return null;
}
}
// 登錄服務器事件
public void btnlogin_Click()
{
ftpUristring = “ftp://” + ftppath;
networkCredential = new NetworkCredential(account, password);
if (ShowFtpFileAndDirectory() == true)
{
Debug.Log(“連接成功”);
}
else
{
Debug.Log(“連接shibai”);
}
}
void OnDestroy()
{
// for (int i = 0; i < DataReader.idNames.Count; i++)
// {
// File.Delete(Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + ".jpg");
// }
// for (int i = 0; i < DataReader.idNames.Count; i++)
// {
// File.Delete(Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + "Qrcode" + ".jpg");
// }
// string datPath = Application.streamingAssetsPath + Timecheck() + “.dat”;
//File.Delete(datPath);
Resources.UnloadUnusedAssets();
GC.Collect();
}
public string GetUriString(string filename)
{
string uri = string.Empty;
if (currentDir.EndsWith("/"))
{
uri = ftpUristring + currentDir + filename;
}
else
{
uri = ftpUristring + currentDir + “/” + filename;
}
return uri;
} // 從服務器上下載文件到本地事件
public void btndownload_Click(string date)
{
for (int i = 0; i < 100; i++)
{
string fileName = “/home/jifenshangcheng/goods/” + date + “/” + i.ToString() + “.jpg”;
if (fileName.Length == 0)
{
Debug.Log(0);
return;
}
// 選擇保存文件的位置
string filePath = Application.streamingAssetsPath + “/Shopping/” + DataReader.idNames[i] + “.jpg”; //要具體到名字
try
{
string uri = GetUriString(fileName);
FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.DownloadFile);
FtpWebResponse response = GetFtpResponse(request);
if (response == null)
{
return;
}
Stream responseStream = response.GetResponseStream();
FileStream filestream = File.Create(filePath);
int buflength = 8196;
byte[] buffer = new byte[buflength];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = responseStream.Read(buffer, 0, buflength);
filestream.Write(buffer, 0, bytesRead);
}
Debug.Log(“下載成功”);
responseStream.Close();
filestream.Close();
}
catch (WebException ex)
{
Debug.Log(“下載失敗”);
}
}
}
現在代碼還是我以前工程裏的代碼,暫未做修改,可以根據我這個demo測試一下 然後進行修改:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;// 添加命令空間using System.Net;using System.Text;
using System.Net;
using System.Text;
public class GetSceneFromFTP : MonoBehaviour
{
private int ftpport = 21;
private string ftpUristring = null;
private NetworkCredential networkCredential;
public string ftppath;
private string currentDir = “/”;
public string downname;
public GameObject content;
public GameObject content1;
public GameObject content2;
//public string[] picPath;
//public string[] QrcodePath;
private string account;
private string password;
public string datepath;
public List<Sprite> list_sprite = new List<Sprite>();
// Use this for initialization
void Awake()
{
}
void Start()
{
}
// Update is called once per frame
public void Init()
{
btnlogin_Click();
btndownload_Dat(Timelib());
}
void Update()
{
//if (Input.GetKeyDown(KeyCode.A))
//{
// if (iss)
// {
// getpath();
// Debug.Log(content.transform.childCount);
// Debug.Log(picPath.Length);
// iss = false;
// }
//}
//if (Input.GetKeyDown(KeyCode.D))
// {
// iss = true;
// if (iss)
// {
// for (int i = 0; i < content.transform.childCount; i++)
// {
// StartCoroutine(LoadByWWW(picPath[i], content.transform.GetChild(i).GetComponent<RawImage>()));
// }
// for (int i = 0; i < picPath.Length-60; i++)
// {
// StartCoroutine(LoadByWWW(picPath[i+60], content1.transform.GetChild(i).GetComponent<RawImage>()));
// }
// iss = false;
// }
//}
}
//創建FTP連接
public FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod)
{
FtpWebRequest request = (FtpWebRequest) FtpWebRequest.Create(uri);
request.Credentials = networkCredential;
request.KeepAlive = true;
request.UseBinary = true;
request.Method = requestMethod;
return request;
}
// 獲取服務器返回的響應體
public FtpWebResponse GetFtpResponse(FtpWebRequest request)
{
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) request.GetResponse();
return response;
}
catch (WebException ex)
{
return null;
}
}
// 登錄服務器事件
public void btnlogin_Click()
{
ftpUristring = "ftp://" + ftppath;
networkCredential = new NetworkCredential(account, password);
if (ShowFtpFileAndDirectory() == true)
{
Debug.Log("連接成功");
}
else
{
Debug.Log("連接shibai");
}
}
// 顯示資源列表
public bool ShowFtpFileAndDirectory()
{
try
{
string uri = string.Empty;
if (currentDir == "/")
{
uri = ftpUristring;
}
else
{
uri = ftpUristring + currentDir;
}
uri = "ftp://" + ftppath;
FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.ListDirectoryDetails);
// 獲得服務器返回的響應信息
FtpWebResponse response = GetFtpResponse(request);
Debug.Log(response);
if (response == null)
{
return false;
} // 讀取網絡流數據
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, Encoding.Default);
string s = streamReader.ReadToEnd();
streamReader.Close();
stream.Close();
response.Close();
// 處理並顯示文件目錄列表
string[] ftpdir = s.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int length = 0;
for (int i = 0; i < ftpdir.Length; i++)
{
if (ftpdir[i].EndsWith("."))
{
length = ftpdir[i].Length - 2;
break;
}
}
for (int i = 0; i < ftpdir.Length; i++)
{
s = ftpdir[i];
int index = s.LastIndexOf('\t');
if (index == -1)
{
if (length < s.Length)
{
index = length;
}
else
{
continue;
}
}
string name = s.Substring(index + 1);
if (name == "." || name == "..")
{
continue;
}
// 判斷是否爲目錄,在名稱前加"目錄"來表示
if (s[0] == 'd' || (s.ToLower()).Contains("<dir>"))
{
string[] namefield = name.Split(' ');
int namefieldlength = namefield.Length;
string dirname;
dirname = namefield[namefieldlength - 1];
dirname = dirname.PadRight(34, ' ');
name = dirname;
}
}
for (int i = 0; i < ftpdir.Length; i++)
{
s = ftpdir[i];
int index = s.LastIndexOf('\t');
if (index == -1)
{
if (length < s.Length)
{
index = length;
}
else
{
continue;
}
}
string name = s.Substring(index + 1);
if (name == "." || name == "..")
{
continue;
}
// 判斷是否爲文件
if (!(s[0] == 'd' || (s.ToLower()).Contains("<dir>")))
{
string[] namefield = name.Split(' ');
int namefieldlength = namefield.Length;
string filename;
filename = namefield[namefieldlength - 1];
// 對齊
filename = filename.PadRight(34, ' ');
name = filename;
// 顯示文件
}
}
return true;
}
catch
{
return false;
}
}
void OnDestroy()
{
for (int i = 0; i < DataReader.idNames.Count; i++)
{
File.Delete(Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + ".jpg");
}
for (int i = 0; i < DataReader.idNames.Count; i++)
{
File.Delete(Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + "Qrcode" + ".jpg");
}
string datPath = Application.streamingAssetsPath + Timecheck() + ".dat";
File.Delete(datPath);
Resources.UnloadUnusedAssets();
GC.Collect();
}
#region
public string GetUriString(string filename)
{
string uri = string.Empty;
if (currentDir.EndsWith("/"))
{
uri = ftpUristring + currentDir + filename;
}
else
{
uri = ftpUristring + currentDir + "/" + filename;
}
return uri;
}
public void btndownloadQRCODE_Click(string date)
{
for (int i = 0; i < DataReader.idNames.Count; i++)
{
string fileName = datepath + date + "/" + DataReader.idNames[i] + "QRCode.png";
if (fileName.Length == 0)
{
Debug.Log(0);
return;
}
// 選擇保存文件的位置
string filePath =
Application.streamingAssetsPath + "/Qrcode/" + DataReader.idNames[i] + "QRCode.png"; //要具體到名字
try
{
string uri = GetUriString(fileName);
FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.DownloadFile);
FtpWebResponse response = GetFtpResponse(request);
if (response == null)
{
Debug.Log(1);
return;
}
Stream responseStream = response.GetResponseStream();
FileStream filestream = File.Create(filePath);
int buflength = 8196;
byte[] buffer = new byte[buflength];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = responseStream.Read(buffer, 0, buflength);
filestream.Write(buffer, 0, bytesRead);
}
responseStream.Close();
filestream.Close();
}
catch (WebException ex)
{
Debug.Log("下載失敗");
}
}
} // 獲得選擇的文件
// 從服務器上下載文件到本地事件
public void btndownload_Click(string date)
{
//for (int i = 0; i < DataReader.idNames.Count; i++)
//{
// string fileName = datepath + date + "/" + DataReader.idNames[i] + ".jpg";
// Debug.Log(DataReader.idNames[i]);
// if (fileName.Length == 0)
// {
// Debug.Log(0);
// return;
// }
for (int i = 0; i < 100; i++)
{
string fileName = "/home/jifenshangcheng/goods/" + date + "/" + i.ToString() + ".jpg";
if (fileName.Length == 0)
{
Debug.Log(0);
return;
}
// 選擇保存文件的位置
string filePath = Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + ".jpg"; //要具體到名字
try
{
string uri = GetUriString(fileName);
FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.DownloadFile);
FtpWebResponse response = GetFtpResponse(request);
if (response == null)
{
return;
}
Stream responseStream = response.GetResponseStream();
FileStream filestream = File.Create(filePath);
int buflength = 8196;
byte[] buffer = new byte[buflength];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = responseStream.Read(buffer, 0, buflength);
filestream.Write(buffer, 0, bytesRead);
}
Debug.Log("下載成功");
responseStream.Close();
filestream.Close();
}
catch (WebException ex)
{
Debug.Log("下載失敗");
}
}
} // 獲得選擇的文件
public void btndownload_Dat(string date)
{
string fileName = datepath + date + Timecheck() + ".dat";
if (fileName.Length == 0)
{
Debug.Log(0);
return;
}
// 選擇保存文件的位置
string filePath = Application.streamingAssetsPath + Timecheck() + ".dat"; //要具體到名字
try
{
string uri = GetUriString(fileName);
FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.DownloadFile);
FtpWebResponse response = GetFtpResponse(request);
if (response == null)
{
Debug.Log(1);
return;
}
Stream responseStream = response.GetResponseStream();
FileStream filestream = File.Create(filePath);
int buflength = 8196;
byte[] buffer = new byte[buflength];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = responseStream.Read(buffer, 0, buflength);
filestream.Write(buffer, 0, bytesRead);
}
responseStream.Close();
filestream.Close();
}
catch (WebException ex)
{
Debug.Log("下載失敗");
}
}
// 獲得選擇的文件
// // 如果選擇的是目錄或者是返回上層目錄,則返回null//該函數要掛在Button上
public string GetSelectedFile()
{
string filename = downname;
return filename;
} // 刪除服務器文件事件
IEnumerator CreatSprite(byte[] buffer, RawImage sp)
{
int width = 1080;
int height = 640;
Texture2D t = new Texture2D(width, height);
t.LoadImage(buffer);
sp.texture = t;
yield return new WaitForSeconds(0.01f);
// sp = Sprite.Create(t,new Rect(0,0, width, height),new Vector2(0.5f,0.5f) );
//list_sprite.Add(sp);
}
public IEnumerator LoadByWWW(string path, RawImage raw)
{
string path1 = "file://" + path;
WWW www = new WWW(path1);
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
Texture2D texture = www.texture;
raw.texture = texture;
// sprite.Add(Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)));
// sprite=Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
else
{
Debug.Log(www.error);
}
}
//public void getpath(string)
//{
// picPath = Directory.GetFiles(Application.streamingAssetsPath + "/Shopping/", "*.jpg", SearchOption.AllDirectories);
// QrcodePath= Directory.GetFiles(Application.streamingAssetsPath + "/Qrcode/", "*.png", SearchOption.AllDirectories);
//}
#endregion
public string Timelib()
{
DateTime a = DateTime.Now;
string datepath = string.Format("{0:yyyyMMdd}", a);
return datepath;
}
public string Timecheck()
{
DateTime a = DateTime.Now;
string.Format("{0:yyyyMMdd}", a);
string datepath = "/GOODS_" + string.Format("{0:yyyyMMdd}", a);
return datepath;
}
public IEnumerator _readIP()
{
WWW www = new WWW("file://" + Application.streamingAssetsPath + "/ipconfig.txt");
yield return www;
if (string.IsNullOrEmpty(www.error))
{
string[] infoArray = www.text.Split('\n');
foreach (string str in infoArray)
{
if (!str.Contains("@"))
continue;
string[] allArray = str.Split('@');
ftppath = allArray[1];
ftpport = int.Parse(allArray[3]);
datepath = allArray[5];
account = allArray[7];
password = allArray[9];
}
//if (string.IsNullOrEmpty(www.error))
//{
// string[] infoArray = www.text.Split('\n');
// Dictionary<string, string> infoDic = new Dictionary<string, string>();
// foreach (string str in infoArray)
// {
// string[] allArray = str.Split('@');
// string id = allArray[0];
// string info = allArray[1].Replace("\r", "");
// infoDic.Add(id, info);
// // Debug.Log(infoDic[id]);
// }
// foreach (var str in infoDic.Keys)
// {
// Debug.Log(str);
// }
// ftppath = infoDic["ip"];
// ftpport = int.Parse(infoDic["port"]);
// datepath = infoDic["datepath"];
// account = infoDic["account"];
// password = infoDic["password"];
Init();
DataReader.instance.dateinit();
btndownload_Click(Timelib());
btndownloadQRCODE_Click(Timelib());
for (int i = 0; i < content.transform.childCount; i++)
{
StartCoroutine(LoadByWWW(
Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i] + ".jpg",
content.transform.GetChild(i).GetChild(1).GetComponent<RawImage>()));
}
if (DataReader.idNames.Count > 60)
{
for (int i = 0; i < DataReader.idNames.Count - 60; i++)
{
Debug.Log(1);
StartCoroutine(LoadByWWW(
Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i + 60] + ".jpg",
content1.transform.GetChild(i).GetChild(1).GetComponent<RawImage>()));
}
}
if (DataReader.idNames.Count > 120)
{
for (int i = 0; i < DataReader.idNames.Count - 120; i++)
{
Debug.Log(2);
StartCoroutine(LoadByWWW(
Application.streamingAssetsPath + "/Shopping/" + DataReader.idNames[i + 120] + ".jpg",
content2.transform.GetChild(i).GetChild(1).GetComponent<RawImage>()));
}
}
}
}
}