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

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

问题描述

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

 私人无效StartListening()
{
,而(运行)
{
AcceptingSocket.Listen(100);
客户端的Socket = AcceptingSocket.Accept();

如果(!IncomingConnection = NULL)
{
TcpEventArgs的EventArgs =新TcpEventArgs(客户端);
IncomingConnection(EventArgs的);
}
}
}



有没有一种方式,如果用户希望接受或拒绝的连接?


解决方案
<。接受检查p>由于@Blindy说,你需要接受传入连接,然后将其关闭,如果你决定,你不希望与该连接进行。直到接受的回报,你不必在插座,所以无法做任何会一个参考将允许你做出决定是否或不接受,基于客户端(如支票提供的凭据或源地址的连接)。



从客户的角度来看,一旦他们连接到收听 ING插座,连接建立(建立连接到由操作系统的监听端口,然后交给你在接受调用)。你可以不假了连接被拒绝/对方主动拒绝了连接上插座是处于监听状态类型的错误。因此,接受后跟关闭,会看起来是一样的客户,如果有一些方法为接受中止连接。



如果你有一个纲领性的理由不允许更多的连接(比如你只想一次一个客户端),那么你可以关闭听它接受后的连接,而这通常是一个坏主意 ING插座。


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.

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

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