2

因此,使用我的软件,我在网络上发送了一个发现广播,每个接收到该广播的“客户端”都将通过 TCP 连接到我。就我所拥有的而言,它似乎可以“正常”工作,但我觉得必须有更好的方法。我看到的是我的软件的一些 TCP 连接被拒绝(我认为),因为我目前正在接受另一个套接字。因此,使用我当前的版本,我可以在大约 80% 的时间接受套接字。有时更多,但通常在 80% 左右。其余的都被我的软件拒绝了,我不知道为什么。对我来说,这是不可接受的,但我很讨厌提高这个数字。

这是我用来接受 TCP 客户端并通知我的其他类有关已连接的新套接字的类:

public class AsynchronousSocketListener
{
    // Thread signal.
    public ManualResetEvent allDone = new ManualResetEvent(false);
    public event EventHandler<ErtdRawDataArgs> ClientConnected;

    private string bindingIp;
    public string AddressBind 
    {
        get { return this.bindingIp; } 
        private set { this.bindingIp = value; } 
    }

    private int port;
    public int Port
    {
        get { return this.port; }
        private set { this.port = value; }
    }

    private Socket listener;

    public AsynchronousSocketListener(string bindingIp, int port) 
    {
        this.bindingIp = bindingIp;
        this.port = port;
    }

    protected void OnClientConnected(string data, IPEndPoint clientEP)
    {
        if (this.ClientConnected == null)
            return;

        Task.Factory.StartNew(() =>
        {
            //build args
            ErtdRawDataArgs args = new ErtdRawDataArgs(Encoding.Default.GetBytes(data));
            args.Source = string.Format("{0}:{1}", clientEP.Address.ToString(), clientEP.Port);
            this.ClientConnected(this, args);
        });
    }

    public void Close()
    {
        if (this.listener == null || !this.listener.Connected)
            return;

        this.listener.Shutdown(SocketShutdown.Both);
        this.listener.Close();
    }

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

            // Establish the local endpoint for the socket.
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(this.bindingIp), this.port);

            // Create a TCP/IP 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);
                int maxConnections = (int)SocketOptionName.MaxConnections;
                listener.Listen(maxConnections);

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

                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

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

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

    public 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);
    }

    public void ReadCallback(IAsyncResult ar) 
    {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket. 
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            // There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(
                state.buffer,0,bytesRead));

            // Check for end-of-file tag. If it is not there, read 
            // more data.
            content = state.sb.ToString();
            OnClientConnected(content, handler.RemoteEndPoint as IPEndPoint);

            //close socket
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
    }
}

有什么方法可以改进此代码,或者是否有一些完全不同的东西可以改善我同时接受 TCP 连接的结果?

4

1 回答 1

1

好吧,您在接受连接和“建立”连接之间有一段时间,然后您才能接受另一个连接。使用等待句柄之类的东西可能相当慢。

重新阅读您的代码后,从概念上讲,您可以接受另一个连接的时间点是您调用EndAccept. 看来您是在调用之前设置事件,EndAccept这意味着BeginAccept可以在调用之前调用,并且可以在调用前EndAccept一个连接之前接受另一个连接EndAccept。我不知道这是否是一个问题——据我所知,这是合法的。但是,您可以简化代码以避免事件,并在当前接受期间简单地链接下一个 BeginAccept 并确保EndAccept在下一个之前调用BeginAccept

我所做的是从当前接受中链接下一个接受。 例如:

listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 62000));
listener.Listen(1000);
listener.BeginAccept(OnAccept, listener);

private void OnAccept(IAsyncResult ar)
{
    Socket listener = (Socket)ar.AsyncState;
    Socket socket = listener.EndAccept(ar);
    listener.BeginAccept(OnAccept, listener);
    socket.BeginReceive(new byte[10], 0, 10, 0, (arReceive) => socket.EndReceive(arReceive), null);
}

当然,我在BeginAcceptSocket这里使用;但这个概念与BeginAccept...相同

This frees you from having to start a new Task, frees from creating wait handles which are about 50-times slower that lock because they are cross-process--which frees you from having a "huge" pause between accepts.

于 2012-09-05T19:08:01.847 回答