Socket.Shutdown throws a SocketException

I am trying to implement async sockets for my project. Here is the code

    public void Start(int listeningPort)
    {
        var ipHostInfo = Dns.Resolve(Dns.GetHostName());
        var ipAddress = ipHostInfo.AddressList[0];
        var localEndPoint = new IPEndPoint(ipAddress, listeningPort);

        _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _listener.Bind(localEndPoint);
        _listener.Listen(3000);
        Started = true;

        Task.Factory.StartNew(() =>
        {
            while (Started)
            {
                allDone.Reset();

                _listener.BeginAccept(AcceptCallback, _listener);

                allDone.WaitOne();
            }
        });
    }

    public void Stop()
    {
        Started = false;
        _listener.Shutdown(SocketShutdown.Both); //<-- throws SocketException
        _listener.Close(2000);
        _listener = null;
    }

    public void Kick(IClient client)
    {
        try
        {
            Clients.Remove(client);
            client.Socket.Shutdown(SocketShutdown.Both);
            client.Socket.Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket handler = null;
        try
        {
            allDone.Set();

            var listener = (Socket) ar.AsyncState;
            handler = listener.EndAccept(ar);

            var client = new Client(this, handler);
            Clients.Add(client);

            var state = new StateObject();
            state.Socket = handler;
            handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, state);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            var client = ClientBySocket(handler);
            if(handler != null && client != null) Kick(client);
        }
    }

    private void ReadCallback(IAsyncResult ar)
    {
        Socket handler = null;
        try
        {
            var state = (StateObject) ar.AsyncState;
            handler = state.Socket;

            var bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {
                if (Received != null)
                {
                    var buff = new byte[bytesRead];
                    if (buff[0] == 0)
                    {
                        Stop();
                    }
                    return;
                    Array.Copy(state.Buffer, buff, bytesRead);
                    Debug.WriteLine(Encoding.UTF8.GetString(buff));
                    try
                    {
                        Received(this, new ReceiveArgs(buff));
                    }
                    catch(Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            }
            handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, state);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            var client = ClientBySocket(handler);
            if (handler != null && client != null) Kick(client);
        }
    }

but every time I call Stop (which, in turn, causes shutdown) (regardless of whether clients are connected or not), Socket.Shutdown throws a SocketException with a message

Additional information: a request to send or receive data was denied, because the socket was not connected and (when sending to a datagram socket using the sendto call) the address was not sent

I am really stuck here. Does anyone know what I'm doing wrong?

+4
source share
1 answer

. , . , , , . .

Shutdown .

Btw, Accept async IO, . . .

+5

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


All Articles