【问题标题】:C# - System.Net Socket.Listen BacklogC# - System.Net Socket.Listen 待办事项
【发布时间】:2012-04-26 10:42:34
【问题描述】:

好的,我已使用以下代码连接到 IP 地址:

        IPAddress myIpAddress = IPAddress.Parse("10.10.15.200");

        IPEndPoint ip = new IPEndPoint(myIpAddress, 5001);
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(ip);

我现在想监听套接字。当我输入 socket.Listen 时,intellisense 说我需要输入一个积压数,这是什么意思?

另外,一旦我在监听套接字,我如何捕获我正在“监听”的内容。

谢谢

约翰

【问题讨论】:

标签: c# sockets listen


【解决方案1】:

您可以使用 BeginAccept 来读取到达您的套接字/端点的内容。

在 MSDN 上有一个完整的例子,这里:Socket.BeginAccept Method

// This server waits for a connection and then uses asynchronous operations to
    // accept the connection with initial data sent from the client.


    // Establish the local endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry(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.
    listener.Bind(localEndPoint);
    listener.Listen(100);

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

        // Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...");

        // Accept the connection and receive the first 10 bytes of data.
        int receivedDataSize = 10;
        listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);

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

}


public static void AcceptReceiveCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;

    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);

    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);

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

【讨论】:

  • 谢谢你,但是我有一个问题。我们从哪里得到“allDone”?我可能只是遗漏了一些明显的东西,但如果能指出我正确的方向,那就太好了。谢谢你
  • 查看 msdn 文章中的链接。如果找不到定义的位置,可能可以将其删除
  • 这就是我要做的,因为它根本没有在链接中定义,非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
相关资源
最近更新 更多