conexión de la unidad de ftp

protocolo FTP Unidad está cargado


Protocolo de Transferencia de Archivos (Inglés: Protocolo de transferencia de archivos, abreviatura: FTP) es un protocolo estándar para la transferencia de archivos a través de la red, utilizando un modelo cliente / servidor. Pertenece a la capa de aplicación del protocolo de transmisión de la red. La diferencia entre la transferencia de archivos (transferencia de archivos), y acceso a archivos (acceso a archivos): el primero es proporcionada por el FTP, NFS, etc. Este último es proporcionado por los sistemas de aplicación.
FTP es un cliente de 8 bits - protocolo de servidor, puede operar cualquier tipo de archivo sin la necesidad de tratamiento adicional, lo mismo que Unicode o MIME. Sin embargo, FTP tiene extremadamente alta latencia, lo que significa que el tiempo entre la recepción de los datos de demanda de la solicitud para iniciar la primera vez, será muy largo, y de vez en cuando tiene que realizar algún proceso de inicio de sesión larga.
Este artículo es la unidad de conexión del servidor FTP, puede descargar FileZilla Server para crear un servidor ftp, los detalles pueden Baidu.

// Crear una conexión FTP
público CreateFtpWebRequest la FtpWebRequest (URI String, String requestMethod)
{
la Solicitud FtpWebRequest = (el FtpWebRequest) FtpWebRequest.Create (URI);
request.Credentials = NetworkCredential;
request.KeepAlive = true;
request.UseBinary = true;
request.method requestMethod =;
Solicitud de retorno;
}
// obtener el servidor devuelve el cuerpo de la respuesta
pública del FtpWebResponse GetFtpResponse (la Solicitud FtpWebRequest)
{
la respuesta FtpWebResponse = NULL;
el try
{
respuesta = (el FtpWebResponse) request.GetResponse ();
return respuesta;
}
la captura (el WebException EX)
{
devolver null;
}
}
// eventos de registro del servidor
public void btnlogin_Click) (
{
ftpUristring = “ftp: //” + ftppath;
NetworkCredential = nuevo NetworkCredential (cuenta, contraseña);
si (ShowFtpFileAndDirectory () == true)
{
debug.log ( “连接成功”);
}
Demás
{
debug.log ( “连接shibai”);
}
}
OnDestroy void ()
{
// 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");

//}
// cadena datPath = Application.streamingAssetsPath + Timecheck () + “.dat”;
//File.Delete (datPath);
Resources.UnloadUnusedAssets ();
GC.Collect ();
}
Public String GetUriString (string filename)
{
string uri = String.Empty;
si (currentDir.EndsWith ( "/"))
{
uri = ftpUristring + currentDir + nombre de archivo;
}
Demás
{
uri = ftpUristring + currentDir + “/” + nombre del archivo;
}
Uri regresar;
} //从服务器上下载文件到本地事件
vacío btndownload_Click (fecha de cadena) pública
{
for (int i = 0; i <100; i ++)
{
string filename = “/ home / jifenshangcheng / bienes /” + fecha + “/” + i.ToString () + “.jpg”;
si (fileName.Length == 0)
{
debug.log (0);
regreso;
}
//选择保存文件的位置
cadena rutaArchivo = Application.streamingAssetsPath + “/ Compras /” + DataReader.idNames [i] + “.jpg”; //要具体到名字
try
{
string uri = GetUriString (nombre del archivo);
Solicitud FtpWebRequest = CreateFtpWebRequest (URI, WebRequestMethods.Ftp.DownloadFile);
Respuesta FtpWebResponse = GetFtpResponse (petición);
si (respuesta == null)
{
return;
}
Corriente responseStream = response.GetResponseStream ();
FileStream filestream = File.Create (filePath);
int buflength = 8,196;
byte [] amortiguar = new byte [buflength];
int BytesRead = 1;
mientras que (BytesRead = 0)
{
BytesRead = responseStream.Read (buffer, 0, buflength);
filestream.Write (buffer, 0, BytesRead);
}
Debug.log ( “下载成功”);
responseStream.Close ();
filestream.Close ();
}
Catch (WebException ex)
{
debug.log ( “下载失败”);
}
}
}

Ahora código o el código en mi proyecto anterior, sin embargo, para hacer cambios, entonces puede ser modificado de acuerdo a mi prueba de demostración:
una utilizando los System.Collections;
un uso System.Collections.Generic;
un uso UnityEngine;
un uso UnityEngine.UI;
un using System;
un uso el System.IO ; // añadir un espacio de comandos utilizando un System.Net ; un uso System.Text;
un uso de System.Net ;
un uso System.Text;

GetSceneFromFTP clase pública: MonoBehaviour
{
int ftpport privado = 21;
cadena privada ftpUristring = null;
NetworkCredential NetworkCredential privado;
ftppath cadena pública;
currentDir private string = “/”;
downname cadena pública;
GameObject contenido público;
pública 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>()));
            }
        }

    }
}

}

Publicado cuatro artículos originales · ganado elogios 1 · vistas 1334

Supongo que te gusta

Origin blog.csdn.net/obf2018/article/details/88943702
Recomendado
Clasificación