473,804 Members | 3,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is wrong with BeginReceive?

1 New Member
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.

Expand|Select|Wrap|Line Numbers
  1. private static void BeginReceiving()
  2.         {
  3.             //client is an instance of 'Socket'
  4.             try
  5.             {
  6.                 Monitor.Enter(client);
  7.                 // Create the state object.
  8.                 StateObject state = new StateObject();
  9.  
  10.                 // Begin receiving the data from the remote server.
  11.                 client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None/*0*/,
  12.                     new AsyncCallback(ContinueReceiving), state);
  13.             }
  14.  
  15.             catch (System.Exception ex)
  16.             {
  17.                       //code clipped
  18.             }
  19.             finally
  20.             {
  21.                 if (client != null) Monitor.Exit(client);
  22.             }
  23.         }
  24. //---------------------------------------------------------------------
  25.         private static void ContinueReceiving(IAsyncResult ar)
  26.         {
  27.             try
  28.             {
  29.                 // Retrieve the state object from the asynchronous state object.
  30.                 StateObject state = (StateObject)ar.AsyncState;
  31.  
  32.                 // Read data from the remote device.
  33.                 int bytesRead = client.EndReceive(ar);
  34.                 if (bytesRead > 0)
  35.                 {
  36.                     //
  37.                     // There might be more data, so store the data received so far.
  38.                                state.reveivedData.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  39. //ETX is a pre-defined constant -- by it, I know I've received a complete message from the server
  40.                     if (state.reveivedData.ToString().IndexOf(Globals.ETX) > -1)//I reached the end of sent data
  41.                     {
  42.  
  43.                        //start parsing the message
  44.                        //code clipped
  45.  
  46.                     }
  47.                     else //there still more data in the current message received from the server
  48.                     {
  49.                         // Get the rest of the data.
  50. /*THE EXTREME BEHAVIOR HAPPENS HERE */
  51.                         client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE,  SocketFlags.None/*0*/,
  52.                             new AsyncCallback(ContinueReceiving), state);
  53.                     }
  54.                 }
  55.             }
  56.             catch (System.Exception ex)
  57.             {
  58.                 //code clipped
  59.             }
  60.             finally
  61.             {
  62.             }
  63.         }
  64. //--------------------------------------------------------------
  65. // State object for receiving data from server.
  66. public class StateObject
  67. {
  68.     // Size of receive buffer.
  69.     public const int BUFFER_SIZE = 256;
  70.     // Receiving buffer.
  71.     public byte[] buffer = new byte[BUFFER_SIZE];
  72.     // Received data string.
  73.     public StringBuilder reveivedData = new StringBuilder();
  74. }
  75.  
- when the message is smaller the BUFFER_SIZE, it works properly
- The problem happens when the message's length is greater than the BUFFER_SIZE. When I debugged the code I found that the code doesn't work properly when I want to receive more data to complete the message (i.e. I am waiting for the ETX). In this case I send the state object [which contains the data received so far] with the AsyncCallback to appending more data to it.
Unfortunately, reveivedData (which is a StringBuilder member in the StateObject to concatenate data received in it) found empty the next cycle i received data (although it was working properly when I was installing .NET 2.0 only)

-------------------------------------
Any help will be greatly appreciated...
thanks in advance
Jan 28 '08 #1
0 1203

Sign in to post your reply or Sign up for a free account.

Similar topics

3
10484
by: TP-Software | last post by:
Hi, This code doesn't seem to work it always says "there is more data" and also this method is only called once private void AsyncReadCallBack(IAsyncResult asyncResult) {
0
1607
by: faktujaa | last post by:
Hi All, I have used the available code snippet from microsoft for socket communication. But the following code throws an error mentioned above. Please check the code and help me asap. private static void ReceiveCallback(IAsyncResult IResult) { try { // Retrieve the state object and the client socket from the
0
4231
by: ?lafur Helgi R?gnvaldsson | last post by:
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 ManualResetEvent to signal the main thread when data arrives. Here is the code I'm running: using System;
0
1738
by: J Brad | last post by:
Hi every body I wrote a Asynch Server using ManualResetEvent.Reset(), ManualResetEvent.Set(), ManualResetEvent.WaitOne() events I'm receiving a Message (Example: "Hello Word") without Terminator (No Char or String Terminator like <EOF>) So When I Receive my Message ((Example: "Hello Word") ), My seconde call "handler.BeginReceive()" will not call the ReadCallback() delegate Is there any way to control the end of reading of the message...
1
2561
by: Marty | last post by:
Hi, I have a socket that always seek for incoming data. Between Point A and Point B, the socket (mySocket is closed and assigned to nothing in another part of my program (happen when a connection is broken). So regurlarly when a socket is closed, it create an error somewhere in this routine, even if I check if the socket is nothing or not, and connected or not (I also tried to check before doing the beginreceive)
4
3306
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...
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...
2
6544
by: O.B. | last post by:
In the following code snippet, the thread successfully makes it to the line where it waits for data to be received. Then the client closes the connection. The thread wakes up and returns from the WaitOne() operation. No exception is thrown when it loops and executes BeginReceive() again. The WaitOne() operation returns immediately. Thus, there's an endless loop. How does one detect that the remote client has closed the connection in...
5
2304
by: Ryan Liu | last post by:
Hi, I read Microsoft SDK, ms-help://MS.NETFrameworkSDKv1.1/cpguidenf/html/cpovrasynchronousprogramming overview.htm there are 4 ways to call EndInvoke: The code in this topic demonstrates four common ways to use BeginInvoke and EndInvoke to make asynchronous calls. After calling BeginInvoke you can:
0
9705
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
10323
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...
0
10074
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
9138
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
7613
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
6847
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
5515
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...
1
4291
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
3
2983
bsmnconsultancy
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.

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