Rasheed Abdul
Rasheed Abdul

Reputation: 49

Listening socket - connecting socket gets connected without debug breaking at EndAccept

I have issue in .NET C#, multi threaded socket application.

After some time randomly, connection are accepted without executing the call back function and doesn't come to beginaccept.

The code for listener and callback function is as given below.

    public void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, listenPort);//Listen on all available network interfaces

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.
        bool signal = true;
        try
        {
            listener.Bind(localEndPoint);       
            listener.Listen(listenPort);

            while (startlisten)
            {
                // Set the event to nonsignaled state.
                allDone.Reset();
                if (signal)
                {
                    // Start an asynchronous socket to listen for connections.
                    string s = string.Format("Server Socket: Waiting for a connection at Port:{0}", listenPort);
                    DisplayMsg(s);
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);
                }
                // Wait until a connection is made before continuing.
                signal = allDone.WaitOne(100);
            }
            listener.Close();
        }
        catch (Exception e)
        {
            if (e is System.Net.Sockets.SocketException)
            {
                SocketException socex = (e as SocketException);

                throw new Exception(socex.Message);
            }
            else
            {
                throw new Exception(e.Message);
            }
        }
    }

    public void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.

        try
        {
            if (startlisten)
            {
                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;

                TCPClient tcp = frm.GetClientObj();
                tcp.socketForServer = listener.EndAccept(ar);

                DisplayErrorMsg("Connection Request From: " + tcp.socketForServer.RemoteEndPoint.ToString());

                tcp.Connected = true;
                tcp.ReceiveData();

                // Create the state object.
                //                StateObject state = new StateObject();
                //                state.workSocket = handler;
                //                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                //                    new AsyncCallback(ReadCallback), state);
            }
        }
        catch (Exception e)
        {
            if (e is System.Net.Sockets.SocketException)
            {
                SocketException socex = (e as SocketException);

                DisplayErrorMsg(socex.Message);
            }
            else
            {
                DisplayErrorMsg(e.Message);
            }
        }
        allDone.Set();

    }

Upvotes: 1

Views: 1409

Answers (2)

Rasheed Abdul
Rasheed Abdul

Reputation: 49

I found the answer, it was related to the allDone event, should signaled inside the if loop.

if (signal)
{
    allDone.Reset();
    // Start an asynchronous socket to listen for connections.
    string s = string.Format("Server Socket: Waiting for a connection at Port:{0}", listenPort);
    DisplayMsg(s);
    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}

// Wait until a connection is made before continuing.
signal = allDone.WaitOne(100);

Upvotes: 0

Konstantin Salavatov
Konstantin Salavatov

Reputation: 4540

this happen if you close listening socket before EndAccept

"To cancel a pending call to the BeginAccept method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled."

http://msdn.microsoft.com/en-us/library/5bb431f9.aspx

Upvotes: 1

Related Questions