473,791 Members | 3,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling BeginReceive with receive pending

I'm building a server application which accepts socket connections and
I ran into some problems.

The socket is asynchronous and therefore uses the BeginXXX and EndXXX
methods in the Socket class to receive data. I also use a
ManualResetEven t to signal the main thread when data arrives.

Here is the code I'm running:

using System;
using System.Net;
using System.Net.Sock ets;
using System.Threadin g;
using System.Text;

namespace SocketClient
{
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder() ;
}

class SocketClient
{
private const int port = 11000;
private bool timeout = true;

private ManualResetEven t connectDone = new ManualResetEven t(false);
private ManualResetEven t sendDone = new ManualResetEven t(false);
private ManualResetEven t receiveDone = new ManualResetEven t(false);

[STAThread]
static void Main(string[] args)
{
SocketClient socketClient = new SocketClient();
socketClient.St artClient();
Console.ReadLin e();
}

private void StartClient()
{
try
{
IPHostEntry ipHostInfo = Dns.Resolve("lo calhost");
IPAddress ipAddress = ipHostInfo.Addr essList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAd dress, port);

Socket client = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);

client.BeginCon nect( remoteEP, new AsyncCallback(C onnectCallback) ,
client);
connectDone.Wai tOne();

for(int i=0; i<3; i++)
{
Send(client,"Th is is a test<EOF>" + i);
sendDone.WaitOn e();

Receive(client) ;
receiveDone.Wai tOne(3000, true);

if(timeout == true)
{
Console.WriteLi ne("Timed out...");
}
else
{
Console.WriteLi ne("Response received");
}
}
client.Shutdown (SocketShutdown .Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
}

private void ConnectCallback (IAsyncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;
client.EndConne ct(ar);
connectDone.Set ();
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
}

private void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocke t = client;

client.BeginRec eive( state.buffer, 0, StateObject.Buf ferSize, 0,
new AsyncCallback(R eceiveCallback) , state);
timeout = true;
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
}

private void ReceiveCallback ( IAsyncResult ar )
{
try
{
timeout = false;
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocke t;

int bytesRead = 0;
try
{
bytesRead = client.EndRecei ve(ar);
}
catch(ObjectDis posedException)
{
//the socket has been closed
}

if (bytesRead > 0)
{
state.sb.Append (Encoding.ASCII .GetString(stat e.buffer,0,byte sRead));
receiveDone.Set ();
}
else
{
//disconnected
receiveDone.Set ();
}
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
}

private void Send(Socket client, String data)
{
byte[] byteData = Encoding.ASCII. GetBytes(data);
client.BeginSen d(byteData, 0, byteData.Length , 0, new
AsyncCallback(S endCallback), client);
}

private void SendCallback(IA syncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;
int bytesSent = client.EndSend( ar);
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLi ne(e.ToString() );
}
}
}
}

The code above works fine and the server only sends data back to the
client when "This is a test<EOF>2" is received otherwise I have a
timeout. The output of this is:
Timed out...
Timed out...
Response received

However the beginReceive function is called twice without the
ReceiveCallback function being called. The ReceiveCallback function
is only called the third time the server sends the data back to the
client. When the client.Close() function is called the
ReceiveCallback function is called twice, since there were 2 receive
functions pending. The ReceiveCallback function calls EndReceive
which in turn throws an ObjectDisposedE xception which I catch and
ignore.

Here is my question, is this the proper way to implement a timeout
with an asynchronous socket or is it a bad idea to call beginReceive
with a pending receive ?

Ólafur Helgi.
Nov 15 '05 #1
0 4229

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

Similar topics

1
2578
by: Lee Gillie | last post by:
What is the proper way to cancel a pending BeginReceive/EndReceive ? Can it be done without generating an exception ? Currently I shutdown and close the socket. The blocking "EndReceive" throws System.ObjectDisposedException. I try to avoid throwing exceptions when ever possible, and reserve them for unanticipated problems. Trying to stop a background read/process loop is an anticipated activity. For me the debugger delays 15...
2
9235
by: dream machine | last post by:
Hi all , with BegeinReceive I can build async method of Socket Class that Receive the data from the Socket Client . My question is , if I have this code that create 3 Receive Async Call : <code> mySocket.BeginReceive(param1,param2,param3.....); mySocket.BeginReceive(param1,param2,param3......); mySocket.BeginReceive(param1,param2,param3......);
6
13152
by: Steve Richter | last post by:
I dont get the point of socket.BeginReceive and socket.EndReceive. As I understand it, BeginReceive will start a 2nd thread, call the ReceiveCallback delegate in the 2nd thread, then block until the socket.EndReceive method called in the 2nd thread receives some data from the socket. If the 1st thread will block until the 2nd thread receives some data from the socket, what is the point of starting up the 2nd thread? I am aware I can...
4
3305
by: Ryan Liu | last post by:
TcpClient has a method called GetworkStream GetStream(); So in other words, there is only one stream associate with it for input and output, right? So while it is receiving, it can not send, and vise visa, right? So will it be a problem both server and client can initiative a sending action? TcpClient only supports synchronous operation. What does "Synchronous" mean? Means while it is reading or waiting for data to arrive from the...
5
5015
by: Jason Richmeier | last post by:
I have been unable to locate an answer for this question because (1) it is late in the day and my eyes are tired of looking at code and documentation, (2) I am new to this area of the .NET framework, or (3) a combination of (1) and (2). I am looking at using messaging in an application I am working on. I have been reading the documentation about messaging and have been able to understand just about everything that I have read so far. I...
2
2274
by: Marcel Brekelmans | last post by:
Hi, I use a socket to receive data from a certain process. I use the asynchronous operations BeginReceive() and EndReceive(), with a callback in BeginReceive. Now all documentation says that the callback, as specified in BeginReceive, is called as soon as 'the data is received'. But this is rather vague: when exactly is that moment if you don't know how exactly that other process is providing data? One criterium is that BeginReceive()...
9
7333
by: semedao | last post by:
Hi, I am using sync and async operations on the same socket. generally I want the socket to wait on BeginReceive and to not block the object thread. but in some cases I want to stop the BeginReceive in the middle - Don't accept any data from it , and using regular Receive (I don't want the data will come to the BeginReceive byte buffer , instead of other buffer) then when I comlete some operaion , to return and call to the BeginReceive...
22
4044
by: semedao | last post by:
Hi , I am using asyc sockets p2p connection between 2 clients. when I debug step by step the both sides , i'ts work ok. when I run it , in somepoint (same location in the code) when I want to receive 5 bytes buffer , I call the BeginReceive and then wait on AsyncWaitHandle.WaitOne() but it is signald imidiatly , and the next call to EndReceive return zero bytes length , also the buffer is empty. here is the code: public static byte...
0
1203
by: sameh serag | last post by:
Hi all, I have a problem with .NET sockets... The code snippet bellow was working fine with .NET 2.0. After I installed .NET 3.0 it didn't work properly. private static void BeginReceiving() { //client is an instance of 'Socket' try {
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10428
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...
1
10156
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
9997
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...
0
9030
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
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
6776
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
5435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.