正在写关于邮箱连接的东西,但是测试用户名和密码的时候总是要卡1-2S才出现结果。
很疑惑,不是应该很快就有响应的么,网速正常。检查一下代码吧,发现耗时的操作不是在streamReader里面读取数据时的READLINE().而是创建tcpclient时的new tcpClient最耗时,求高手指点一下。对networkStream也设置了timeout=1000,原来不设置的时候密码部分一错误就要卡死很长时间。
连接代码如下:
     public bool Connect()
        {
            if (_host == "")
                throw new Exception("请提供SMTP主机名称或IP地址!");
            if (_port == null)
                throw new Exception("请提供SMTP主机的端口号");
            try
            {
                _tcpClient = new TcpClient(_host, _port);
                _netStream = _tcpClient.GetStream();
                _netStream.ReadTimeout = 1000;
                _stmReader = new StreamReader(_tcpClient.GetStream());                string strMessage = _stmReader.ReadLine();
                if (CheckCorrect(strMessage, "+OK") == true)
                    return true;
                else
                    return false;
            }
            catch (SocketException exc)
            {
                throw new Exception(exc.ToString());
            }
            catch (NullReferenceException exc)
            {
                throw new Exception(exc.ToString());
            }        }        private string ExecuteCommand(string command)
        {
            string strMessage = null; //执行Pop3命令后返回的消息            try
            {
                //发送命令
                WriteToNetStream(ref _netStream, command);                //读取多行
                if (command.Substring(0, 4).Equals("LIST") || command.Substring(0, 4).Equals("RETR") || command.Substring(0, 4).Equals("UIDL")) //记录STAT后的消息(其中包含邮件数)
                {
                    strMessage = ReadMultiLine();                    if (command.Equals("LIST")) //记录LIST后的消息(其中包含邮件数)
                        _StatMessage = strMessage;
                }
                //读取单行
                else
                    strMessage = _stmReader.ReadLine();                //判断执行结果是否正确
                if (CheckCorrect(strMessage, "+OK"))
                    return strMessage;
                else
                    return "Error";
            }
            catch (IOException exc)
            {
                throw new Exception(exc.ToString());
            }
        }邮箱tcpclient

解决方案 »

  1.   

    public bool Connect(string _host, int _port)
    bool concedt = Connect("121.205.88.228",110);
    我帮你测试了一下Connect不卡啊,是不是你的网络有问题,如果网络有问题把Connect写到线程里或用异步连接好了
      

  2.   

    不是卡,是感觉那个BOX出来的没有那么快的说,网络很好写到线程里面过一会再蹦出来着实麻烦,请问异步连接应该怎么做呢?因为我想做的效果是验证完用户的输入账号信息后,配置窗口自动最小化,然后任务栏上面跳出来账号测试的提示气泡框