Hi! This is my first time on Daniweb, and my first time coding a server, too. So I've tried many ways, and finally found a working one - or one that was working, until recently. For an unknown reason, my receival of data doesn't work: The data is received, it gets appended to the stringbuilder, and then, it should invoke a new ReadCallback, in order, this time, for the read bytes to be shown. However, for some reason, the call to the new callback (using a BeginReceive) doesn't work! It just stays there, not doing anything.

Anyhow, here is the code. I know I'm probably unclear, and perhaps a code is more useful. I'm sorry for the many mistakes that might be found across the code, I'm a newcomer to multi-threads, callbacks and asynchronous sockets.

public static void ReadCallback(IAsyncResult ar)
	Console.WriteLine("Debug 0: Creating state object...");
	StateObject State = (StateObject)ar.AsyncState;
	Console.WriteLine("Debug 1: Created state object.");

	Console.WriteLine("Debug 2: Ending receival...");
	int Read = State.Socket.EndReceive(ar);
	Console.WriteLine("Debug 3: Ended receival. Stocked in Read. Read={0}", Read);

	if (Read > 0)
		Console.WriteLine("Debug 4: Read>0. Appending {0} to sb.", Encoding.ASCII.GetString(State.Buffer, 0, Read));
		State.sb.Append(Encoding.ASCII.GetString(State.Buffer, 0, Read));
		Console.WriteLine("Debug 5: Appended string.");

		Console.WriteLine("Debug 6: Beginning new receival...");
		State.Socket.BeginReceive(State.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), State);
		Console.WriteLine("Debug 7: Begun new receival.");
		//WAIT! Here is the error! A new BeginReceive has been launched and should therefore throw a ReadCallback,
		//but it doesn't! It just stays here!
		Console.WriteLine("Debug 4: Read<0.");
		if (State.sb.Length > 1)
			Console.WriteLine("Debug 5: sb length>1. Data of more than 1 char has been read.");
			Console.WriteLine("SUCCESS: Read {0} byte from socket {2}. Data = {1} ", State.sb.ToString().Length, State.sb.ToString(), State.Socket.Handle);
			Console.WriteLine("Debug 5: sb length<1. Not done yet.");
			Console.WriteLine("Reading... Current: {0}", State.sb.ToString());

Thanks for your help! I know this might not be a clear and concise question as the guidelines suggest, however, even after trying to debug my own code, I can't find the source of the problem, so I'm forced to post it all.

Don't be alarmed, for me your post is very correct. You even used code tags!
I don't know if it matters but ReadCallBack is called recursively, see line 19.

This article has been dead for over six months. Start a new discussion instead.