473,796 Members | 2,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.SetSocke tOption(
SocketOptionLev el.Socket,
SocketOptionNam e.ReceiveTimeou t,
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.IOExc eption 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 10738
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()
{
OpenServerSocke t();
ConnectClient() ;
AcceptServer();
ConfigureTimeou t();
OpenInputStream ();

CheckTimeoutOnR ead();
CheckTimeoutOnR ead();

CloseAll();
}

private void CheckTimeoutOnR ead()
{
int start = Environment.Tic kCount;
int stop = 0;
try
{
_inputStream.Re adByte();
}
catch (Exception ex)
{
stop = Environment.Tic kCount;
Console.WriteLi ne(ex);
}

int duration = stop - start;

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

void OpenServerSocke t()
{
_serverSocket = NewSocket();
_serverSocket.B ind(new IPEndPoint(IPAd dress.Any, 0));
_serverSocket.L isten(42);
}

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

void AcceptServer()
{
_server = _serverSocket.A ccept();
}

void ConfigureTimeou t()
{
_server.SetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.ReceiveTimeou t, TIMEOUT);
_server.SetSock etOption(Socket OptionLevel.Soc ket,
SocketOptionNam e.SendTimeout, TIMEOUT);
}

void OpenInputStream ()
{
_inputStream = new NetworkStream(_ server);
}

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

int Port()
{
return ((IPEndPoint)_s erverSocket.Loc alEndPoint).Por t;
}

Socket NewSocket()
{
return new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
}

IPAddress Resolve(string hostName)
{
IPHostEntry found = Dns.Resolve(hos tName);
foreach (IPAddress address in found.AddressLi st)
{
if (address.Addres sFamily == AddressFamily.I nterNetwork)
{
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
52231
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
3314
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 = length
1
3821
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 = ('192.168.1.50', 3333); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect()
1
2341
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, I simply access the self.QuitFlag in lock mode, and set it to 1. Now that you know what I have, I would like to add SRP functionality to the validation of each new connection. What I need to add to my code to get SRP to work? I don't know...
3
4638
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 and then fires a datareceived event. Within the waitingloop there is a timeout function, but I want the the 'last-time-socket-used' variable set when the socket is finished sending. When I send by System.Net.Sockets.Socket.Send(buffer()) (<--this...
6
4126
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: Connect Receive response Send Connect ACK
1
8186
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 the members of my organization. I think my problem is incorrectly setting the settings on my server or an authentication problem. Here is the code I have written to send a test message: -----Code Begins: Sensitive Information Replaced by -----...
0
1644
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) { IAsyncResult result = theSock.BeginReceive(arr, startByte, length, SocketFlags.None, null, null); if (result.AsyncWaitHandle.WaitOne(timeout, false) ==
2
2407
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 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print 'trying to connect...'
0
9524
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10217
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10168
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.