How to reject a connection attempt in c#?

前端 未结 2 1279
旧巷少年郎
旧巷少年郎 2020-12-11 22:11

I have a socket that listens for connections. What I want to do is to have an accept / reject option when a connection is attempted. This is my code:

private         


        
相关标签:
2条回答
  • 2020-12-11 22:21

    You (almost) always want to Accept the connection, because the decision whether or not to connect can only come based on information sent from the client (user name, password, etc).

    So after you establish a connection, run your authorization module to gather the authentication information and based on that, decide whether or not to call Close on client (in your example).

    0 讨论(0)
  • 2020-12-11 22:38

    As @Blindy has said, you need to accept the incoming connection, then close it if you decide that you don't want to proceed with that connection. Until Accept returns, you don't have a reference to the Socket, so are unable to do anything that would allow you to make a decision about whether or not to accept, based on the client (such as check supplied credentials, or the source address for the connection).

    From the client's perspective, once they have connected to the Listening socket, the connection is established (the connection is established to the listening port by the OS, then handed over to you in the Accept call). You cannot fake a 'Connection Refused / The other side actively refused the connection' type error on a Socket that is in a listening state. So Accept, followed by Close, would look the same to the client as if there was some way for Accept to abort the connection.

    If you've got a programmatic reason for not allowing more connections (such as you only want one client at a time), then you could shutdown the Listening socket after it accepts a connection, but this is generally a bad idea.

    0 讨论(0)
提交回复
热议问题