如何在 C# 中拒绝连接尝试? [英] How to reject a connection attempt in c#?

查看:37
本文介绍了如何在 C# 中拒绝连接尝试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个监听连接的套接字.我想要做的是在尝试连接时有一个接受/拒绝选项.这是我的代码:

private void StartListening(){在跑步的时候){AcceptingSocket.Listen(100);套接字客户端 = AcceptingSocket.Accept();如果(传入连接!= null){TcpEventArgs eventArgs = new TcpEventArgs(client);传入连接(事件参数);}}}

.Accept 有没有办法检查用户是要接受还是拒绝连接?

解决方案

正如@Blindy 所说,您需要接受传入的连接,如果您决定不想继续该连接,请关闭它.在 Accept 返回之前,您没有对 Socket 的引用,因此无法做任何事情让您决定是否接受,基于客户端(例如检查提供的凭据或连接的源地址).

从客户端的角度来看,一旦他们连接到Listening套接字,连接就建立起来了(连接是由OS建立到监听端口的,然后在Listen代码>接受调用).您不能在处于侦听状态的 Socket 上伪造连接被拒绝/另一方主动拒绝连接"类型错误.因此,Accept 后跟 Close,对客户端来说看起来是一样的,就好像 Accept 有某种方式可以中止连接.>

如果您有一个不允许更多连接的编程原因(例如您一次只需要一个客户端),那么您可以在接受连接后关闭 Listen 套接字,但这通常是个坏主意.

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

这篇关于如何在 C# 中拒绝连接尝试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆