无法将数据写入传输连接:远程主机强制关闭现有连接

时间:2010-09-05 11:14:34

标签: c# file tcp send

我有一个通过TCP端口12000发送客户端更新的更新服务器。单个文件的发送仅在第一次成功,但之后我在服务器上收到错误消息“无法将数据写入传输连接:远程主机强行关闭现有连接“。如果我在服务器上重新启动更新服务,它只会再次运行一次。我有正常的多线程Windows服务。

服务器代码

namespace WSTSAU
{
    public partial class ApplicationUpdater : ServiceBase
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        private int _listeningPort;
        private int _ApplicationReceivingPort;
        private string _setupFilename;
        private string _startupPath;
        public ApplicationUpdater()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            init();
            logger.Info("after init");
            Thread ListnerThread = new Thread(new ThreadStart(StartListener));
            ListnerThread.IsBackground = true;
            ListnerThread.Start();
            logger.Info("after thread start");
        }

        private void init()
        {
            _listeningPort = Convert.ToInt16(ConfigurationSettings.AppSettings["ListeningPort"]);
            _setupFilename = ConfigurationSettings.AppSettings["SetupFilename"];
            _startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
        }

        private void StartListener()
        {
            try
            {
                logger.Info("Listening Started");
                ThreadPool.SetMinThreads(50, 50);
                TcpListener listener = new TcpListener(_listeningPort);
                listener.Start();
                while (true)
                {
                    TcpClient c = listener.AcceptTcpClient();
                    ThreadPool.QueueUserWorkItem(ProcessReceivedMessage, c);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        void ProcessReceivedMessage(object c)
        {
            try
            {
                TcpClient tcpClient = c as TcpClient;
                NetworkStream Networkstream = tcpClient.GetStream();
                byte[] _data = new byte[1024];
                int _bytesRead = 0;

                _bytesRead = Networkstream.Read(_data, 0, _data.Length);

                MessageContainer messageContainer = new MessageContainer();
                messageContainer = SerializationManager.XmlFormatterByteArrayToObject(_data, messageContainer) as MessageContainer;

                switch (messageContainer.messageType)
                {
                    case MessageType.ApplicationUpdateMessage:
                        ApplicationUpdateMessage appUpdateMessage = new ApplicationUpdateMessage();
                        appUpdateMessage = SerializationManager.XmlFormatterByteArrayToObject(messageContainer.messageContnet, appUpdateMessage) as ApplicationUpdateMessage;
                        Func<ApplicationUpdateMessage, bool> HandleUpdateRequestMethod = HandleUpdateRequest;
                        IAsyncResult cookie = HandleUpdateRequestMethod.BeginInvoke(appUpdateMessage, null, null);
                        bool WorkerThread = HandleUpdateRequestMethod.EndInvoke(cookie);
                        break;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }


        private bool HandleUpdateRequest(ApplicationUpdateMessage appUpdateMessage)
        {
            try
            {
                TcpClient tcpClient = new TcpClient();
                NetworkStream networkStream;
                FileStream fileStream = null;

                tcpClient.Connect(appUpdateMessage.receiverIpAddress, appUpdateMessage.receiverPortNumber);
                networkStream = tcpClient.GetStream();

                fileStream = new FileStream(_startupPath + "\\" + _setupFilename, FileMode.Open, FileAccess.Read);

                FileInfo fi = new FileInfo(_startupPath + "\\" + _setupFilename);

                BinaryReader binFile = new BinaryReader(fileStream);

                FileUpdateMessage fileUpdateMessage = new FileUpdateMessage();
                fileUpdateMessage.fileName = fi.Name;
                fileUpdateMessage.fileSize = fi.Length;

                MessageContainer messageContainer = new MessageContainer();
                messageContainer.messageType = MessageType.FileProperties;
                messageContainer.messageContnet = SerializationManager.XmlFormatterObjectToByteArray(fileUpdateMessage);

                byte[] messageByte = SerializationManager.XmlFormatterObjectToByteArray(messageContainer);

                networkStream.Write(messageByte, 0, messageByte.Length);

                int bytesSize = 0;
                byte[] downBuffer = new byte[2048];

                while ((bytesSize = fileStream.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    networkStream.Write(downBuffer, 0, bytesSize);
                }

                fileStream.Close();
                tcpClient.Close();
                networkStream.Close();

                return true;
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
                return false;
            }
            finally
            {
            }
        }


        protected override void OnStop()
        {
        }
    }

我必须注意我的Windows服务(服务器)是多线程的。

1 个答案:

答案 0 :(得分:0)

在接收端,设置一个while循环来监听,直到没有更多数据,然后正常退出:关闭流和客户端。框架TCP库认为在线程退出时断开连接是一个问题,因此会抛出你​​看到的异常。

这也可以避免您在纠正当前问题后可能会遇到的间歇性问题:使用长度说明符的Stream.Read并不总是每次都为您提供完整的缓冲区。看起来你发送(最多)2kb块并接收到(单次)1kb缓冲区,所以你也可能开始获得XML异常。

如果这还不够详细,请问我会挖掘一些旧的TcpClient代码。