添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
473,883 Members | 1,648 Online

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()
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...");
Console.WriteLi ne("Response received");
client.Shutdown (SocketShutdown .Both);
client.Close();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void ConnectCallback (IAsyncResult ar)
Socket client = (Socket) ar.AsyncState;
client.EndConne ct(ar);
connectDone.Set ();
catch (Exception e)
Console.WriteLi ne(e.ToString() );
private void Receive(Socket client)
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 )
timeout = false;
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocke t;

int bytesRead = 0;
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 ();
//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)
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 4239

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

Similar topics

2580
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...
.NET Framework
9238
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 : mySocket.BeginReceive(param1,param2,param3.....); mySocket.BeginReceive(param1,param2,param3......); mySocket.BeginReceive(param1,param2,param3......);
13160
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...
3308
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...
5019
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...
2276
by: Marcel Brekelmans | last post by: 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()...
7337
by: semedao | last post by: 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...
4056
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...
1205
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'
9778
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,...
11112
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...
10405
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...
9559
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...
5784
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...
5980
by: adsilva | last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like?
4602
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
4205
by: muto222 | last post by: How can i add a mobile payment intergratation into php mysql website. 3228
by: bsmnconsultancy | last post by: In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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