简体   繁体   English

TCPIP服务器单连接

[英]TCPIP server single connection

i am using c# sockets Asynchronous mode. 我正在使用c#套接字异步模式。

i need to serve only one connection in my application from a server point of view. 从服务器的角度来看,我只需要在我的应用程序中提供一个连接。 once one is connected then i would like to refuse any more connection requests. 一旦一个连接,然后我想拒绝任何更多的连接请求。

also the server only serves to connect to a single client. 服务器也仅用于连接到单个客户端。 when the communication is done the server has to be restarted. 通信完成后,必须重新启动服务器。

but from what i have read on the topic, it is not possible to close beginaccept. 但是根据我对该主题的阅读,不可能结束beginaccept。

i would like some ideas regarding how get around this situation. 我想要一些有关如何解决这种情况的想法。

Normally, in the BeginAccept async callback you would call BeginAccept again so that another connection can be accepted. 通常,在BeginAccept异步回调中,您将再次调用BeginAccept ,以便可以接受另一个连接。 However, you can omit this step if you do not want to allow another connection. 但是,如果您不想允许其他连接,则可以省略此步骤。 So that the connection is refused in a timely manner, consider also closing the listening socket in the callback. 为了及时拒绝连接,请考虑在回调中也关闭监听套接字。 The accepted Socket will remain open in this case for you to use even though the listening socket is closed. 在这种情况下,即使监听套接字已关闭,接受的Socket也将保持打开状态,供您使用。

class SocketTest
{
    private Socket m_Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    public void Test()
    {
        m_Listener.Bind(new IPEndPoint(IPAddress.Loopback, 8888));
        m_Listener.Listen(16);
        m_Listener.BeginAccept(AcceptCallback, null);
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket s = m_Listener.EndAccept(ar);
        m_Listener.Close();
        /* Use s here. */
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM