2015-12-07 29 views
0

我嘗試發送帶有TCP客戶端的sslStream的文件。文件大約是250kb。 當我不寫dataLength流,服務器關閉連接我的事情,因爲最大接收緩衝區大小。當我寫入流的dataLength,我沒有例外,但服務器有一個類型的錯誤(連接優雅地關閉)。一個原因是,由於Tcp客戶端關閉事件,服務器 無法接收我發送的數據;這是我的代碼。服務器代碼丟失,我知道,它已經在德爾福與印插座庫writen 這裏是我的代碼c#Tcp客戶端傳輸文件與sslStream

TcpClient sendClient = new TcpClient(serverName, port); 
     LingerOption lingerOption = new LingerOption(true, 20); 
     sendClient.LingerState = lingerOption; 
     using (SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)) 
     { 

      try 
      { 

       sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true); 


       sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n")); 
       sendStream.Flush(); 
       int bytesResp = -1; 
       byte[] buffer = new byte[1024]; 

       bytesResp = sendStream.Read(buffer, 0, buffer.Length); 

       string response = Encoding.UTF8.GetString(buffer, 0, bytesResp); 

       if (response.Trim() == "OK") 
       { 

        sendStream.Write(Encoding.ASCII.GetBytes("Send\r\n")); 

        FileStream inputStream = File.OpenRead(filePath); 
        FileInfo f = new FileInfo(filePath); 
        int size = unchecked((int)f.Length); 


        byte[] byteSize = Encoding.ASCII.GetBytes(size.ToString()); 

        sendStream.Write(byteSize); 
        sendStream.Write(Encoding.ASCII.GetBytes("\r\n")); 

        sendStream.Write(Encoding.ASCII.GetBytes(fileName + "\r\n")); 







        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) 
        { 

         long sum = 0; 
         int count = 0; 
         byte[] data = new byte[1024]; 
         while (sum < size) 
         { 
          count = fs.Read(data, 0, data.Length); 
          sendStream.Write(data, 0, count); 
          sum += count; 

          Array.Clear(data, 0, data.Length); 
         } 
         sendStream.Flush(); 
        } 
        sendStream.Write(Encoding.UTF8.GetBytes("\r\n")); 
        sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n")); 


       } 

       MessageBox.Show("end the procedure"); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 

      finally 
      { 
       if (sendClient.Client.Connected) 
       { 
        sendClient.Client.Disconnect(false); 
        sendClient.Client.Dispose(); 
       } 
      } 

回答

0

我不知道它是否會有所幫助,但我也有類似的問題,使用( ){}由於某種原因,它關閉了sslstream。 所以去除可能

using (SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)){} 

SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);