c# - 自动重新连接异步套接字客户端

标签 c# sockets asynchronous asyncsocket winsockets

我正在使用 C# 编写 Windows 窗体应用程序。我正在使用一个套接字客户端,它以异步方式连接到服务器。 如果连接因任何原因断开,我希望套接字尝试立即重新连接到服务器。 我的接收例程如下所示

        public void StartReceiving()
    {
        StateObject state = new StateObject();
        state.workSocket = this.socketClient;
        socketClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnDataReceived), state);
    }

    private void OnDataReceived(IAsyncResult ar)
    {
        try
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int iReadBytes = client.EndReceive(ar);
            if (iReadBytes > 0)
            {
                byte[] bytesReceived = new byte[iReadBytes];
                Buffer.BlockCopy(state.buffer, 0, bytesReceived, 0, iReadBytes);
                this.responseList.Enqueue(bytesReceived);
                StartReceiving();
                receiveDone.Set();
            }
            else
            {
                NotifyClientStatusSubscribers(false);
            }
        }
        catch (Exception e)
        {

        }
    }

当调用 NotifyClientStatusSubscribers(false) 时,将执行 StopClient 函数:

public void StopClient()
    {
        this.canRun = false;
        this.socketClient.Shutdown(SocketShutdown.Both);
        socketClient.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), this.socketClient);
    }

    private void DisconnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the disconnection.
            client.EndDisconnect(ar);

            this.socketClient.Close();
            this.socketClient = null;
        }
        catch (Exception e)
        {

        }
    }

现在我尝试通过调用以下函数重新连接:

    public void StartClient()
    {
        this.canRun = true;
        this.MessageProcessingThread = new Thread(this.MessageProcessingThreadStart);
        this.MessageProcessingThread.Start();
        this.socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        this.socketClient.LingerState.Enabled = false;
    }

    public void StartConnecting()
    {
        socketClient.BeginConnect(this.remoteEP, new AsyncCallback(ConnectCallback), this.socketClient);
    }

    private void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            // Signal that the connection has been made.
            connectDone.Set();

            StartReceiving();

            NotifyClientStatusSubscribers(true);
        }
        catch(Exception e)
        {
            StartConnecting();
        }
    }

当连接可用时,套接字会重新连接,但几秒钟后,我收到以下未处理的异常: “在已连接的套接字上发出了连接请求。”

这怎么可能?

最佳答案

如果您在 ConnectCallback 中遇到异常并且实际上已成功连接,则有可能。在 ConnectCallback 的 catch 语句中设置一个断点,看看是否有异常发生——目前没有任何信息可以告诉您发生了异常。

关于c# - 自动重新连接异步套接字客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9912303/

相关文章:

sockets - 了解结构 sockaddr

Kotlin 奇怪的分块、异步和等待行为

c# - 如何判断失败的方法调用参数值?

java - Spring - 如何运行一系列线程并等待它们完成后再完成?

c - 绑定(bind)套接字时如何不破坏 UDP 端口?

c# - 如何向 Windows Phone WebBrowser 添加多个 header ?

c# - 用高效代码(可能是 linq)替换 3 层嵌套 for 循环

c# - 具有多态性的通用接口(interface)来处理对象

c# - 从 bouncycaSTLe 导入 RSA key 有时会抛出 "Bad Data"

java - Java socket 多线程安全吗?