c# 再次尝试 连接失败,如何拒绝在C#中连接尝试?

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 void StartListening()

{

while (running)

{

AcceptingSocket.Listen(100);

Socket client = AcceptingSocket.Accept();

if (IncomingConnection!= null)

{

TcpEventArgs eventArgs = new TcpEventArgs(client);

IncomingConnection(eventArgs);

}

}

}

Is there a way that the .Accept checks if the user wants to accept or reject the connection?

解决方案

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 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值