C # ReceiveAsync Error

I am currently developing an application server. I would like to use the AcceptAsync method. I got the error "The reference to the object is not installed in the instance of the object." when calling the ReceiveAsync method. If such a problem arises and you get a solution?

public class AppServer { public void Start() { Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12345)); serverSocket.Listen(100); SocketAsyncEventArgs e = new SocketAsyncEventArgs(); e.Completed += new EventHandler<SocketAsyncEventArgs>(e_Completed); bool raiseEvent = serverSocket.AcceptAsync(e); if (!raiseEvent) AcceptCallback(e); } void e_Completed(object sender, SocketAsyncEventArgs e) { AcceptCallback(e); } private void AcceptCallback(SocketAsyncEventArgs e) { SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(readEventArgs_Completed); Socket clientSocket = e.AcceptSocket; bool raiseEvent = clientSocket.ReceiveAsync(readEventArgs); // <-- Error goes here if (!raiseEvent) ReceiveCallback(readEventArgs); } void readEventArgs_Completed(object sender, SocketAsyncEventArgs e) { ReceiveCallback(e); } private void ReceiveCallback(SocketAsyncEventArgs e) { } } 
+6
source share
2 answers

I had the same problem and managed to figure it out. You need to provide the SocketAsyncEventArgs object with a data buffer (an array of bytes) to store the data received before calling ReceiveAsync (e).

 void e_Completed(object sender, SocketAsyncEventArgs e) { byte[] buffer = new byte[1024]; e.SetBuffer(buffer, 0, buffer.Length); AcceptCallback(e); } 
+7
source

I'm not sure why you accept a socket in two places. If you remove

  AcceptCallback(e); 

from e_Completed everything works.

Link to an example of an asynchronous server:

link

-1
source

Source: https://habr.com/ru/post/890279/


All Articles