我们前台是C#客户端,后台是Java的。如果不知道java的话,就把后台当做C#。 现在明确要求了不用http协议的,要是用的http协议的话,就好点,只需传到网页中,在网页中操作。 所以就只有ftp了,现在对ftp不了解,我能做的是在前台把文件转成文件流,或者二进制流,然后该怎么弄呢? 服务端又该怎么接受?  有接触过FTP协议的,说下思路。 谢谢指点一二。或者有什么例子。

解决方案 »

  1.   

    using System;
    using System.Net;
    using System.Threading;using System.IO;
    namespace Examples.System.Net
    {
        public class FtpState
        {
            private ManualResetEvent wait;
            private FtpWebRequest request;
            private string fileName;
            private Exception operationException = null;
            string status;
            
            public FtpState()
            {
                wait = new ManualResetEvent(false);
            }
            
            public ManualResetEvent OperationComplete
            {
                get {return wait;}
            }
            
            public FtpWebRequest Request
            {
                get {return request;}
                set {request = value;}
            }
            
            public string FileName
            {
                get {return fileName;}
                set {fileName = value;}
            }
            public Exception OperationException
            {
                get {return operationException;}
                set {operationException = value;}
            }
            public string StatusDescription
            {
                get {return status;}
                set {status = value;}
            }
        }
        public class AsynchronousFtpUpLoader
        {  
            // Command line arguments are two strings:
            // 1. The url that is the name of the file being uploaded to the server.
            // 2. The name of the file on the local machine.
            //
            public static void Main(string[] args)
            {
                // Create a Uri instance with the specified URI string.
                // If the URI is not correctly formed, the Uri constructor
                // will throw an exception.
                ManualResetEvent waitObject;
                
                Uri target = new Uri (args[0]);
                string fileName = args[1];
                FtpState state = new FtpState();
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                
                // This example uses anonymous logon.
                // The request is anonymous by default; the credential does not have to be specified. 
                // The example specifies the credential only to
                // control how actions are logged on the server.
                
                request.Credentials = new NetworkCredential ("anonymous","[email protected]");
                
                // Store the request in the object that we pass into the
                // asynchronous operations.
                state.Request = request;
                state.FileName = fileName;
                
                // Get the event to wait on.
                waitObject = state.OperationComplete;
                
                // Asynchronously get the stream for the file contents.
                request.BeginGetRequestStream(
                    new AsyncCallback (EndGetStreamCallback), 
                    state
                );
                
                // Block the current thread until all operations are complete.
                waitObject.WaitOne();
                
                // The operations either completed or threw an exception.
                if (state.OperationException != null)
                {
                    throw state.OperationException;
                }
                else
                {
                    Console.WriteLine("The operation completed - {0}", state.StatusDescription);
                }
            }
            private static void EndGetStreamCallback(IAsyncResult ar)
            {
                FtpState state = (FtpState) ar.AsyncState;
                
                Stream requestStream = null;
                // End the asynchronous call to get the request stream.
                try
                {
                    requestStream = state.Request.EndGetRequestStream(ar);
                    // Copy the file contents to the request stream.
                    const int bufferLength = 2048;
                    byte[] buffer = new byte[bufferLength];
                    int count = 0;
                    int readBytes = 0;
                    FileStream stream = File.OpenRead(state.FileName);
                    do
                    {
                        readBytes = stream.Read(buffer, 0, bufferLength);
                        requestStream.Write(buffer, 0, readBytes);
                        count += readBytes;
                    }
                    while (readBytes != 0);
                    Console.WriteLine ("Writing {0} bytes to the stream.", count);
                    // IMPORTANT: Close the request stream before sending the request.
                    requestStream.Close();
                    // Asynchronously get the response to the upload request.
                    state.Request.BeginGetResponse(
                        new AsyncCallback (EndGetResponseCallback), 
                        state
                    );
                } 
                // Return exceptions to the main application thread.
                catch (Exception e)
                {
                    Console.WriteLine("Could not get the request stream.");
                    state.OperationException = e;
                    state.OperationComplete.Set();
                    return;
                }
               
            }
            
            // The EndGetResponseCallback method  
            // completes a call to BeginGetResponse.
            private static void EndGetResponseCallback(IAsyncResult ar)
            {
                FtpState state = (FtpState) ar.AsyncState;
                FtpWebResponse response = null;
                try 
                {
                    response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                    response.Close();
                    state.StatusDescription = response.StatusDescription;
                    // Signal the main application thread that 
                    // the operation is complete.
                    state.OperationComplete.Set();
                }
                // Return exceptions to the main application thread.
                catch (Exception e)
                {
                    Console.WriteLine ("Error getting response.");
                    state.OperationException = e;
                    state.OperationComplete.Set();
                }
            }
        }
    }
      

  2.   

    “明确要求了不用http协议”的话,就能得出结论说“所以就只有ftp了”?你还是问问做java端的人有什么能力,再决定用什么吧。除了ftp和http,还有很多。例如MSMQ和IBMMQ、POP3/SMTP等等等等。
      

  3.   


    当时就提供了 http,和ftp两种。我就这样说的了,关于“MSMQ和IBMMQ、POP3/SMTP”的可能性很小。
      

  4.   

    http可以不仅仅是网页上上传啊...
    backend[AcceptVerbs(HttpVerbs.Post)]
    public void Push(string id) {
    string appName = id.Split('.')[0];
    string targetFolder = Path.Combine(Server.MapPath("/Apps"), appName);
    if (!Directory.Exists(targetFolder)) {
    Directory.CreateDirectory(targetFolder);
    } var buffer = new byte[4096]; using (FileStream fs = new FileStream(Path.Combine(targetFolder, id), FileMode.Create)) {
    while (true) {
    int r = Request.InputStream.Read(buffer, 0, 4096);
    if (r <= 0) { break; }
    fs.Write(buffer, 0, r);
    }
    }
    }
    frontendnamespace AppGet {
    public class PushCommand : CommandBase {
    protected override void Execute() {
    string uri = string.Format("http://{0}/App/Push/{1}", ConfigurationManager.AppSettings["AppCenter"], Args["-file"]);
    Console.WriteLine(uri);
    HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
    request.Method = "POST"; using (Stream stream = request.GetRequestStream()) {
    var buffer = new byte[4096];
    using (FileStream fs = new FileStream(Args["-file"], FileMode.Open)) {
    while (true) {
    int r = fs.Read(buffer, 0, 4096);
    if (r <= 0) { break; }
    stream.Write(buffer, 0, r);
    }
    }
    } request.GetResponse();
    } private const string DefaultContentType = "application/octet";
    }
    }
      

  5.   

    Java 实现一个 servlet 毫无压力啊。前台 C# 用 HttpWebRequest 进行 multiple-data-form 模拟提交即可。
      

  6.   


    哦!你并没有说java端只有http和ftp两种。你的描述似乎是你自己想出来的似地。客户端的要求很简单,所以在.net都是使用webclient或者webrequest简单地写一下就可以了。#1楼的代码算是非常非常长的,但是意思其实就是那样。
      

  7.   

    你可以看msdn: http://msdn.microsoft.com/zh-cn/library/system.net.webclient(v=vs.80).aspx
    它的例子甚至就是ftp的。而比较麻烦的FtpWebRequest方法,可以看msdn:http://msdn.microsoft.com/zh-cn/library/system.net.ftpwebrequest(v=vs.80).aspx
      

  8.   

    嗯,第一个,msdn写的demo没有明确是ftp的。实际上它的demo没有明确任何协议。但是只要你在url中写对你要的访问的写一个路径,你调用它的UploadFile、UploadData、UploadString等方法就能够向ftp写入数据。而登录方面可以卸载url中,也可以写在验证部分中。其实使用webclient那么就写一行代码就可以了。如果你觉得msdn上的第一个例子没有现成的ftp的,那么就去抄一下后边一个复杂一点的ftpwebrequest的例子吧。