tags:

views:

344

answers:

1

I've written the following code:

    public static void BeginListen( int port )
    {
        IPAddress address = IPAddress.Any;
        IPEndPoint endPoint = new IPEndPoint( address, port );

        m_Socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

        m_Socket.Bind( endPoint );
        m_Socket.Listen( 8 );

        m_Socket.BeginAccept( new AsyncCallback( Accept ), null );
    }

    private static void Accept( IAsyncResult result )
    {
        Socket client = m_Socket.EndAccept( result );

        SocketData state = new SocketData( client, 32767 );

        m_Socket.BeginReceive( state.Buffer, 0, state.Buffer.Length, SocketFlags.None,
            new AsyncCallback( Receive ), state );

        m_Socket.BeginAccept( new AsyncCallback( Accept ), null );
    }

When a client attempts to connect, an error is thrown at the BeginReceive call in Accept():

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

What's causing this? I just can't seem to place it.

Thanks

+1  A: 

You need to call BeginReceive on the Socket returned by EndAccept (in your case client), not the server Socket (in your case m_Socket):

Socket client = m_Socket.EndAccept( result );
// ...
client.BeginAccept( new AsyncCallback( Accept ), null );

There's an example that shows the correct usage on MSDN.

Daniel LeCheminant