473,396 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to continue using a Socket after a timeout?

Hi,

I am trying to get the following behaviour for my Socket connection:

(1) Attempt a blocked read for a defined amount of time.
(2) If a timeout occurs, because no data has been sent to the socket,
throw an exception.
(3) Catch the exception and either go back to (1) or quit reading,
depending on a variety of (user defined) factors.

To implement the above I use:

socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
timeout);

Everything works as expected until the first timeout occurs. When
try to read again after the first timeout, the next exception occurs
immediately, without respecting the timeout setting.

I get a System.IO.IOException with the following Message:
"Unable to read data from the transport connection: A non-blocking
socket operation could not be completed immediately."

Even after I send data to the socket and successfully read data, the
behaviour of throwing an exception immediately when no data is
avaialble does not go away and I never get the socket back to a
state where it obeys the timeout in the read operation.

What am I missing?

Is there some kind of reset button that I can push on a timeout?

Oct 21 '07 #1
2 10638
carl.rosenber...@gmail.com wrote:
I am trying to get the following behaviour for my Socket connection:

(1) Attempt a blocked read for a defined amount of time.
(2) If a timeout occurs, because no data has been sent to the socket,
throw an exception.
(3) Catch the exception and either go back to (1) or quit reading,
depending on a variety of (user defined) factors.
Following up, here is a simple code sampe to reproduce the issue:

class Program
{

static int TIMEOUT = 1500;
Socket _serverSocket;

Socket _server;

Socket _client;

NetworkStream _inputStream;
static void Main()
{
new Program().Run();
}

public void Run()
{
OpenServerSocket();
ConnectClient();
AcceptServer();
ConfigureTimeout();
OpenInputStream();

CheckTimeoutOnRead();
CheckTimeoutOnRead();

CloseAll();
}

private void CheckTimeoutOnRead()
{
int start = Environment.TickCount;
int stop = 0;
try
{
_inputStream.ReadByte();
}
catch (Exception ex)
{
stop = Environment.TickCount;
Console.WriteLine(ex);
}

int duration = stop - start;

Console.WriteLine("Expected timeout: " + TIMEOUT);
Console.WriteLine("Actual timeout: " + duration);
}

void OpenServerSocket()
{
_serverSocket = NewSocket();
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
_serverSocket.Listen(42);
}

void ConnectClient()
{
_client = NewSocket();
_client.Connect(new IPEndPoint(Resolve("localhost"), Port()));
}

void AcceptServer()
{
_server = _serverSocket.Accept();
}

void ConfigureTimeout()
{
_server.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, TIMEOUT);
_server.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.SendTimeout, TIMEOUT);
}

void OpenInputStream()
{
_inputStream = new NetworkStream(_server);
}

void CloseAll()
{
_client.Close();
_server.Close();
_serverSocket.Close();
}

int Port()
{
return ((IPEndPoint)_serverSocket.LocalEndPoint).Port;
}

Socket NewSocket()
{
return new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}

IPAddress Resolve(string hostName)
{
IPHostEntry found = Dns.Resolve(hostName);
foreach (IPAddress address in found.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return address;
}
}
throw new Exception();
}
}

Oct 21 '07 #2
ca**************@gmail.com wrote:
[...]
Even after I send data to the socket and successfully read data, the
behaviour of throwing an exception immediately when no data is
avaialble does not go away and I never get the socket back to a
state where it obeys the timeout in the read operation.

What am I missing?

Is there some kind of reset button that I can push on a timeout?
No. It's unfortunate that the .NET docs aren't more clear about this;
the Winsock docs do a better job. From the docs for SO_RCVTIMEO and
SO_SNDTIMEO (http://msdn2.microsoft.com/en-us/lib...s740476.aspx):

If a send or receive operation times out on a socket,
the socket state is indeterminate, and should not be used;
TCP sockets in this state have a potential for data loss,
since the operation could be canceled at the same moment
the operation was to be completed.

Don't use the ReceiveTimeout property if you want to be able to use the
socket after the timeout occurs.

I think you will be happier if you adjust your thinking to not treat
your "timeout" as an exception. That is, you don't really have an
exception...you have a time-based monitoring situation in which you want
to perform some specific, configurable action after a fixed amount of time.

So, instead of using the timeout property of the socket, just set up
some sort of timer somewhere that executes code after a fixed amount of
time. Only if the actual behavior you want is to cancel the i/o on the
socket would you then close the socket when the timer goes off.

Pete
Oct 21 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Achim Domma | last post by:
Hi, I'm using Python 2.3s timeout sockets and have code like this to read a page from web: request = ... self.page = urllib2.urlopen(request) and later:
0
by: Nagy László Zsolt | last post by:
Hi Python Gurus! Here is a method I used before to receive data over a socket (with Python 2.2): SELECT_GRANULARITY = 0.1 # 0.1 seconds def readdata(self,length,timeout): res = '' remain...
1
by: martinnitram | last post by:
Dear all, following are some piece of my code (mainly create a socket connection to server and loop to receive data): # function to create and return socket def connect(): server_config =...
1
by: dcrespo | last post by:
Hi all, Below, you can see a class that when it receives a host connection, it gets validated. Then, if the validation returns True, then process the request. Also, if I want to stop the server,...
3
by: Robert A. van Ginkel | last post by:
Hello Fellow Developer, I use the System.Net.Sockets to send/receive data (no tcpclient/tcplistener), I made a receivethread in my wrapper, the receivethread loops/sleeps while waiting for data...
6
by: roger beniot | last post by:
I have a program that launches multiple threads with a ThreadStart method like the following (using System.Net.Sockets.Socket for UDP packet transfers to a server): ThreadStart pseudo code: ...
1
by: Eric Sheu | last post by:
Greetings, I have been searching the web like mad for a solution to my SMTP problem. I am using Windows Server 2003 and ASP.NET 2.0 w/ C# to send out e-mails from a web site I have created to...
0
by: rcarmich | last post by:
I am having an issue canceling a beginReceive call on a timeout. For example, the following function: public int ReadBytes(Socket theSock, byte arr, int startByte, int length, int timeout) {...
2
by: Mirko Vogt | last post by:
Hey, it seems that the socket-module behaves differently on unix / windows when a timeout is set. Here an example: # test.py import socket...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.