unity ftp连接

1 篇文章 0 订阅

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>()));
            }
        }

    }
}

}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值