如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接 [英] How to properly disconnect from FTP server with FtpWebRequest

查看:74
本文介绍了如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 ftp 客户端,它在一天中连接数次以从 FTP 服务器检索日志文件.

I've created a ftp client that connects several times during the day to retrieve log files from a FTP server.

问题是几个小时后,我从 FTP 服务器收到一条错误消息(已达到 -421 会话限制..).当我使用 netstat 检查连接时,我可以看到到服务器的多个已建立"连接,即使我已经关闭"了连接.

The Problem is that after a few hours I am getting an error message from the FTP server (-421 session limit reached..). When I check the connections with netstat, I can see several 'ESTABLISHED' connections to the server even though I've "closed" the connection.

当我尝试通过命令行或 FileZilla 执行相同操作时,连接已正确关闭.

When I try to do the same over the command line or FileZilla, the connections are properly closed.

ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Resource Cleanup */

localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;

如何正确关闭/断开连接?我是不是忘了什么?

How can I close/disconnect the connection properly? Did I forget anything?

推荐答案

尝试设置 FtpWebRequest.KeepAlive 属性为 false.如果 KeepAlive 设置为 false,则在请求完成时将关闭与服务器的控制连接.

Try and set the FtpWebRequest.KeepAlive property to false. If KeepAlive is set to false, then the control connection to the server will be closed when the request completes.

ftpWebRequest.KeepAlive = false;

这篇关于如何使用 FtpWebRequest 正确断开与 FTP 服务器的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆