3

There is AcceptAsync for Socket.

Code looks like this:

private Socket _listeningSocket;
private SocketAsyncEventArgs _socketEvent;

private Init()
{
   _socketEvent = new SocketAsyncEventArgs();
   _listeningSocket = ...; // Set up ip, port etc.
   _listeningSocket.Bind(...);
   _listeningSocket.Listen(...);
}

public void StartAccept()
{
   if (_socketEvent.AcceptSocket is not null)
   {
      _socketEvent.AcceptSocket = null;
   }

   if (!_listeningSocket.AcceptAsync(_socketEvent))
   {
       ProcessAccept(_socketEvent);
   }
}

public void StopAccept()
{
   // _listeningSocket.Stop or what ?
}

private void ProcessAccept(SocketAsyncEventArgs socketAsyncEvent)
{
   if (socketAsyncEvent.SocketError == SocketError.Success)
   {
        OnClientAccepted?.Invoke(this, socketAsyncEvent);
        StartAccept();
   }
}

How can I stop accepting and start again? I would love to have something like StopAcceptAsync... Or could you point me some example how to stop accepting with SocketAsyncEventArgs ?

Anna Melashkina
  • 422
  • 2
  • 13
  • `Shutdown` is method that you are looking for. If you would have a `TcpListener` then you would have a `Stop`. (You might consider to call `Close(0)`) – Peter Csala Jun 21 '22 at 11:23
  • When I use `Shutdown` I get error: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.' – Anna Melashkina Jun 21 '22 at 11:56
  • Did you specify the `SocketShutdown` enum to `Receive` as a parameter for the `Shutdown`? – Peter Csala Jun 21 '22 at 11:58
  • Yes. `_listeningSocket.Shutdown(SocketShutdown.Receive);` – Anna Melashkina Jun 21 '22 at 12:02
  • Well that's strange. The exception says that you want to perform an action on an already closed connection... Have you checked the `Connected` flag property before calling `Shutdown`? – Peter Csala Jun 21 '22 at 13:16
  • `Connected` is false. But this is server socket, so it's not connected anywhere. It accepts client sockets. – Anna Melashkina Jun 21 '22 at 13:39

0 Answers0