I used MailKit.Net.Imap to read email in my mail box.
Sometimes I get an exception like that I shared below
System.IO.IOException: Connection timed out ---> System.Net.Sockets.SocketException (110): Connection timed out at MailKit.Net.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) --- End of inner exception stack trace ---
Is there any suggistion to solve this problem?
ImapClient client;
client = new ImapClient();
client.Timeout= (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
Also, I can use timeout property of Imap, this can help me to solve this problem?
You have 2 options:
Increase the timeout using the ImapClient.Timeout property. (That said, 1 minute is less than the default timeout which is 2 minutes)
As Max points out in the comments below, properly handle exceptions and retry (which often will require reconnecting the ImapClient).
Related
I send emails from ASP.NET (4.0) website:
SmtpClient mySMTPClient = new SmtpClient();
mySMTPClient.UseDefaultCredentials = false;
mySMTPClient.Host = "email.privateemail.com";
mySMTPClient.Port = 465; //I also tried 587 and none of them
mySMTPClient.Credentials = new System.Net.NetworkCredential("contact#xxxxxx.com", "xxxxxxxxxx");
mySMTPClient.EnableSsl = true;
mySMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mySMTPClient.Send(email);
I send a dozen of emails / day and not in batch or in loop. Only about half of them are sent. The other fail with error:
ERROR MESSAGE: Failure sending mail.
INNER EXCEPTION: System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
The failing emails are random. I don't have a pattern.
Windows server 2008 SP2 build 6002
Firewall PfSense - engineer says rules are configured properly, otherwise all emails would fail.
3rd part email provider: they say everything is configured properly with them and they cannot make any modification on their side anyways.
I am not a network engineer and I don't have one. My question is, what do I do to find the root cause so I can address it?
By now I tried Process Monitor but it doesn't help me (or I don't know how to look).
I found several articles on this problem, none help me by now as their solutions don't apply to my context (I tried some with no success).
Thank you
This is an issue with NameCheap, I'm sick and tired of their email service, they won't fix it, my code runs fine on Gmail and Hotmail but every now and then fails when using NameCheap's SMTP server with " Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Configuration on a single machine:
I have single server node
<ignite xmlns="http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection" gridName="myGrid1">
<clientConnectorConfiguration port="10800"/>
<discoverySpi type="TcpDiscoverySpi" localPort='48500' localPortRange='1'>
<ipFinder type="TcpDiscoveryStaticIpFinder">
<endpoints>
<string>127.0.0.1:48500</string>
</endpoints>
</ipFinder>
</discoverySpi>
<communicationSpi type='TcpCommunicationSpi' localPort='48100' />
And thin client node:
Ignition.StartClient(new IgniteClientConfiguration { Host = "127.0.0.1", Port = 10800})
So I'm trying to make a next test:
1) shutdown server node
2) start server node againg
3) check connection from client node to server node
The problem is after 2 step when I call method
ignite.GetCache<long,Entity>("cacheName").TryGet(id, out item)
I get an exception
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size
at Apache.Ignite.Core.Impl.Client.ClientSocket.SendRequest(RequestMessage& reqMsg) at Apache.Ignite.Core.Impl.Client.ClientSocket.DoOutInOp[T](ClientOp opId, Action1 writeAction, Func2 readFunc, Func3 errorFunc) at Apache.Ignite.Core.Impl.Client.Cache.CacheClient2.DoOutInOp[T](ClientOp opId, Action1 writeAction, Func2 readFunc
at Apache.Ignite.Core.Impl.Client.Cache.CacheClient`2.TryGet(TK key, TV& value)
I am afraid that automatic reconnect is not supported by .Net thin client.
From the source code, Client is created once right away, which does Handshake once right away. There's no reconnect code in sight. There is an issue filed about Failover feature in Apache Ignite JIRA: not just reconnect, but try different node addresses.
This means you will have to check for disconnects and reconnect manually.
I'm writing a bot for moderating my twitch.tv channel in C#.
Here's the basic code for the loop, which is done by a background worker to avoid UI freezes. There's a TCPClient (Client), StreamReader (Reader), StreamWriter (Writer), and NetworkStream (Stream).
private void listener_dowork(object sender, DoWorkEventArgs e)
{
string Data = "";
while ((Data = Reader.ReadLine()) != null)
{
//Perform operations on the received data
}
Console.WriteLine("Loop ended");//this shouldn't happen
}
private void listener_workercompleted(object sender, RunWorkerCompletedEventArgs e)
{
//basically, display a console message that says "OOPS!" and try to reconnect.
}
I get the message "Loop ended" and "OOPS!" and at that point, I get the exception (which I cannot for the life of me catch).
The thing is, I can physically unplug the network cable from my computer wait 30 seconds and plug it back in, and it'll continue just fine.
The full exception is:
System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
Note the lack of a line number, which is present in every other kind of exception I've had, which means I have no idea which part of the program is causing the exception, even though I've put every possible line inside a try/catch.
I guess what I'm looking for is some insight into why this is occurring.
It happens invariably every time I start the bot and leave it running for a few minutes on any channel, though the number of minutes varies.
As I already said in the comments Twitch.tv uses IRC as underlying system for their chat. In order to stay connected with the server you need to reply to "PING" requests that are frequently sent by the server (usually every 30 seconds, may vary depending on the servers implementation). You can read up more about the IRC client protocol in RFC 2812.
You said you already have a StreamWriter and Reader, all you need to do is check if the line contains "PING" and reply with a "PONG":
if (Data.Contains("PING"))
{
_streamWriter.WriteLine(Data.Replace("PING","PONG");
_streamWriter.Flush();
}
I've written an application that in part can download files from a specific web service. The code utilizes an HttpClient to make the calls. The problem is that occasionally I will get a failed request with the following exception message:
Unable to read data from the transport connection: The connection was closed.
I did run across these blog posts, in which the author had to revert the protocol version to 1.0, disable keep alive, and limit the number of service point connections:
http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/
http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/
I followed those instructions, as best I knew how and still got the error. I also made sure to keep a single instance of the HttpClient around (following the Singleton principle).
What is interesting is that when running Fiddler I've yet to get the error, which makes me think that there is something that can be done on the client side since Fiddler appears to be doing something to keep the connection alive (though the issue is so sporadic this may be a red herring).
A couple more notes:
The error invariably occurs in the middle of a download (never when initiating the request).
The file continues to download up to the point of failure (there are no extended pauses or delays first).
--UPDATE--
The error occurs on the following line:
responseTask.Wait(cancellationTokenSource.Token);
The following is the full exception:
System.AggregateException occurred HResult=-2146233088 Message=One
or more errors occurred. Source=mscorlib StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Form1.StartDownload() in c:\Projects\Visual Studio 2012\Demo\Demo\Form1.cs:line 88 InnerException:
System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Error while copying content to a stream.
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.Handlers.ProgressStream.EndRead(IAsyncResult
asyncResult)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
InnerException:
--UPDATE #2--
I thought I would try changing the completion option from 'content read' to 'headers read'. This also failed with the same exception, albeit in a different location (where the TODO comment is, reading the content stream).
--UPDATE #3--
I can confirm that the web service (which is hosted in IIS) is aborting the connections (the IIS logs show a win32 status code of 1236 - ERROR_CONNECTION_ABORTED). To try and narrow things down, the MinFileBytesPerSec metabase property was set to zero (on the off chance the client stopped pulling down data momentarily) and the connection is still being aborted. I've double checked all the timeouts and buffer sizes I can think of to no avail. Clawing at thin air at the moment. Any ideas would be appreciated.
Client Setup:
private void SetupClient()
{
// In case we're taxing the web server, limit the number
// connections we're allowed to make to one.
ServicePointManager.DefaultConnectionLimit = 1;
// Set up the progress handler so that we can keep track of the download progress.
_progressHandler = new ProgressMessageHandler();
_progressHandler.HttpReceiveProgress += ProgressHandler_HttpReceiveProgress;
// Create our HttpClient.
_client = HttpClientFactory.Create(_progressHandler);
_client.BaseAddress = new Uri("http://localhost");
_client.Timeout = TimeSpan.FromMinutes(30);
_client.DefaultRequestHeaders.TransferEncodingChunked = true;
}
Download Logic:
private void StartDownload()
{
// Create the request.
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Download"))
{
// Revert the protocol version and turn off keep alive in accordance with:
// http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/
// http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/
request.Version = new Version("1.0");
request.Headers.Add("Keep-Alive", "false");
// Set the cancellation token's timeout to 30 minutes.
int timeoutInMilliseconds = 30 * 60 * 1000;
using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeoutInMilliseconds))
{
// Making sure that the message isn't "complete" until everything is read in so we can cancel it at anytime.
Task<HttpResponseMessage> responseTask = _client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
responseTask.Wait(cancellationTokenSource.Token);
using (HttpResponseMessage response = responseTask.Result)
{
if (!response.IsSuccessStatusCode)
{
throw new Exception("Request failed!");
}
Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
using (Stream contentStream = streamTask.Result)
{
// TODO: Save to disk.
}
}
}
}
}
I am getting what looks like a timeout exception when using a BlockingDequeue on a RedisTypedClient.
The calling code looks like
using (var client = ClientPool.GetClient())
return client.As<TMessage>().Lists[_channel].BlockingDequeue(timeout);
Where the timeout is set to 0 and the ClientPool is a PooledRedisClientManager.
The stack trace looks like
ServiceStack.Redis.RedisResponseException: No more data, sPort: 51100, LastCommand:
at ServiceStack.Redis.RedisNativeClient.CreateResponseError(String error)
at ServiceStack.Redis.RedisNativeClient.ReadMultiData()
at ServiceStack.Redis.RedisNativeClient.SendExpectMultiData(Byte[][] cmdWithBinaryArgs)
at ServiceStack.Redis.RedisNativeClient.BRPop(String listId, Int32 timeOutSecs)
at ServiceStack.Redis.Generic.RedisTypedClient`1.BlockingDequeueItemFromList(IRedisList`1 fromList, Nullable`1 timeOut)
at ServiceStack.Redis.Generic.RedisClientList`1.BlockingDequeue(Nullable`1 timeOut)
From what I can find, this is an issue with the client holding an open connection. I thought this was supposed to be fixed by using the PooledRedisClientManager, but it seems to still happen. The issue is easy to reproduce. Simply call the BlockingDequeue method and wait about 2-3 minutes and the exception throws.
I had this once on Windows Azure and on redis i did config set timeout 30 and in ServiceStack.Redis i did
var redisFactory = new PooledRedisClientManager(redisConn);
redisFactory.ConnectTimeout = 5;
redisFactory.IdleTimeOutSecs = 30;
And now for some reason it works
It turns out we were sending our Redis requests through a dns entry that was pointing towards an F5 Big IP traffic controller that was setup to drop idle connections after 300 seconds. Once we increased the timeout on the Big IP the error stopped occurring.