【问题标题】:Does closing a spun off async socket make the listener stop listening?关闭分拆的异步套接字是否会使侦听器停止侦听?
【发布时间】:2012-03-19 16:58:42
【问题描述】:

以下摘自 msdn 上的示例:

public static void StartListening() {
    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // Establish the local endpoint for the socket.
    // The DNS name of the computer
    // running the listener is "host.contoso.com".
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint and listen for incoming connections.
    try {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true) {
            // Set the event to nonsignaled state.
            allDone.Reset();

            // Start an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept( 
                new AsyncCallback(AcceptCallback),
                listener );

            // Wait until a connection is made before continuing.
            allDone.WaitOne();
        }

    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static void AcceptCallback(IAsyncResult ar) {
    // Signal the main thread to continue.
    allDone.Set();

    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Create the state object.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
        new AsyncCallback(ReadCallback), state);
}

在 AcceptCallback 方法中关闭从 AsyncState 创建的套接字是否会关闭在 StartListening 方法中创建的侦听器套接字?

真的我的问题是,如果我在线程池上分离套接字接收,对数据做一些事情,然后关闭套接字,我实际上是关闭整个服务器还是只关闭与该客户端的连接?

【问题讨论】:

    标签: c# sockets asynchronous network-programming


    【解决方案1】:

    每个接受的连接都会获得一个新的套接字。完成后,您将其关闭。听众会一直听下去。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2018-11-20
      • 2021-12-30
      • 2011-04-29
      • 2011-12-10
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多