0

I am using Asynchronous Server Socket Example

There is another post which is exactly what I am experiencing, but can't find proper solution: Stackoverflow post

I need to pass additional information, strings from StartListening() function all the way to ReadCallback function. So If I am correct, additional information (strings) should go from StartListening to AcceptCallback and then from AcceptCallback to ReadCallback so in ReadCallback I can finally use passed strings.

listener.BeginAccept(new AsyncCallback(AcceptCallback), listener) 

and

handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

already have parameters assigned (listener and state) which doesn't allow me to pass more parameters.

I think List can be used to pass multiple objects and strings, but how exactly it should be done to pass and, later use required data.

I tried to create List:

var listenerObject = new List<object>();
listenerObject.Add(new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp));
listenerObject.Add(AdditionalParameter);

How to make it work to pass data to AcceptCallback and ReadCallback functions?

  • Typically, you would just create a single object that contains all information you want to be able to use in the callback, and then pass that object as the async state for the operation. That said, you can always use an anonymous method as the callback instead, and then in that anonymous method call the real callback method with whatever parameters you want. See duplicate. – Peter Duniho May 06 '21 at 08:36
  • Thank you for the answer, I understand it in theory, but how the code should look like in my case? I am using the exact example from https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example –  May 06 '21 at 08:38
  • In the example you are looking at, they use the `listener` value as the sole async state value, passing it to the `BeginAccept()` method. You would, instead, create a user-defined type that includes a `Socket Listener { get; }` property, as well as any other properties that you want the accept callback to have access to, create an instance of that user-defined type, and then pass _that_ instead of the `listener` value. In the callback, you would cast the `ar.AsyncState` property to your user-defined type instead of `Socket` as the example does. Simple as that. – Peter Duniho May 06 '21 at 16:38

0 Answers0