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
- private static void BeginReceiving()
- {
- //client is an instance of 'Socket'
- try
- {
- Monitor.Enter(client);
- // Create the state object.
- StateObject state = new StateObject();
- // Begin receiving the data from the remote server.
- client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None/*0*/,
- new AsyncCallback(ContinueReceiving), state);
- }
- catch (System.Exception ex)
- {
- //code clipped
- }
- finally
- {
- if (client != null) Monitor.Exit(client);
- }
- }
- //---------------------------------------------------------------------
- private static void ContinueReceiving(IAsyncResult ar)
- {
- try
- {
- // Retrieve the state object from the asynchronous state object.
- StateObject state = (StateObject)ar.AsyncState;
- // Read data from the remote device.
- int bytesRead = client.EndReceive(ar);
- if (bytesRead > 0)
- {
- //
- // There might be more data, so store the data received so far.
- state.reveivedData.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
- //ETX is a pre-defined constant -- by it, I know I've received a complete message from the server
- if (state.reveivedData.ToString().IndexOf(Globals.ETX) > -1)//I reached the end of sent data
- {
- //start parsing the message
- //code clipped
- }
- else //there still more data in the current message received from the server
- {
- // Get the rest of the data.
- /*THE EXTREME BEHAVIOR HAPPENS HERE */
- client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, SocketFlags.None/*0*/,
- new AsyncCallback(ContinueReceiving), state);
- }
- }
- }
- catch (System.Exception ex)
- {
- //code clipped
- }
- finally
- {
- }
- }
- //--------------------------------------------------------------
- // State object for receiving data from server.
- public class StateObject
- {
- // Size of receive buffer.
- public const int BUFFER_SIZE = 256;
- // Receiving buffer.
- public byte[] buffer = new byte[BUFFER_SIZE];
- // Received data string.
- public StringBuilder reveivedData = new StringBuilder();
- }
- 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