2014-01-07 33 views
-1

我已经创建了一个通过TcpClient发送SSL的包装器。总之,连接我做了这种方式:例外en SSL连接

Stream _stream = null; 

TcpClient _tcpClient = new TcpClient(IPAddress.ToString(), Port); 

if (isSsl) 
{ 
    SslStream sslStream = new SslStream(_tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), new LocalCertificateSelectionCallback(SelectLocalCertificate)); 

    if (Certificate != null) 
    {        
     X509CertificateCollection cc = new X509CertificateCollection(); 
     cc.Add (Certificate); 
     sslStream.AuthenticateAsClient(_Host, cc, SslProtocols.Default, false); 
    } 
    else 
    { 
     sslStream.AuthenticateAsClient(_Host); 
    } 

    sslStream.WriteTimeout = 5000;       
    _stream = (SslStream)sslStream; 
} 
else 
{ 
    NetworkStream networkStream = _client.GetStream(); 
    _stream = (NetworkStream)networkStream; 
} 

要发送,我做的:

_stream.Write(dgram, 0, dgram.Length);  

不时,我有此消息的异常:

异常:无法将数据写入传输连接:连接尝试失败,因为连接方在一段时间后未正确响应,或者由于连接的主机未响应而导致建立的连接失败。

内部异常:连接尝试失败,因为连接的方没有正确一段时间后响应或已建立的连接和失败,因为连接的主机没有反应

堆栈跟踪

at System.Net.Sockets.NetworkStream.Write(Byte [] buffer,Int32 offset,Int32 size) at System.Net.Security._SslStream.StartWriting(Byte [] buffer,Int32 offset,Int32 count,AsyncProtocolRequest asyncRequest)在System.Net.Security上的 .SslStream.ProcessWrite(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.Write(Byte [] buffer,Int32 offset,Int32 count) at MyCompany.Net.IGTcpClient。发送(字符串消息)

我发送好几条消息,然后随机,我有这个例外。现在,当我收到此异常时,我关闭连接并再次打开。我可以从另一段时间发送消息,直到异常再次提升。

当我关闭连接,我做的:

if (_stream != null) 
{ 
    _stream.Close(); 
} 
if (_tcpClient != null) 
{ 
    _tcpClient.Close(); 
} 

我不知道的原因。有关这个例外的原因的任何想法?

在此先感谢

+0

异常的原因是_in_例外:_“连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接的主机未能响应而建立的连接失败”_。确保端口可以访问并且套接字正在监听。 – CodeCaster

+0

是的,端口可以访问,并且套接字正在监听。实际上,我发送了几封邮件,然后随机发送,我有这个例外。现在,我关闭连接并再次打开。 – J19

+0

你在使用什么环境?多少个核心?操作系统版本/版本? IIS/IIS Express?我注意到你没有关闭你的流,并且在某些配置中你可能只有3个并发流的限制。 – Aron

回答

0

阿龙的评论是正确的,你需要关闭这些流。在关闭之后,Socket会暂停一段时间,并且可能是服务器端已经认为它与客户端有连接,但事实上并非如此。使用后关闭流将确保下一次良好的“开放”。

更新 - 我到达,但超时值增加到10秒(从五)。

+0

我已更新主帖以反映此问题。谢谢 – J19