调用EndReceive和BeginReceive

时间:2018-03-12 20:56:18

标签: c# .net tcplistener

我试图实现包装类,它只是连接到TCP服务器并等待数据。一旦从服务器提交数据 - 我将收到这些数据并将其传递给我班级的订阅者。

这一切都有效。现在我想添加外部功能到"重置"计时器上的这个类(每隔一段时间强制重新连接)以保持连接活动。我的想法是可以根据需要多次调用Init方法来重置套接字。但是,我确实得到了各种例外。

课程代码:

namespace Ditat.GateControl.Service.InputListener
{
    using System;
    using System.ComponentModel;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    public class BaseTCPSocketListener : IInputListener
    {
        #region Events/Properties

        public event EventHandler<Exception> OnError;

        public event EventHandler<string> OnDataReceived;

        private string host;

        private int port;

        private int delayToClearBufferSeconds = 5;

        private TcpClient client;

        private readonly byte[] buffer = new byte[1024];

        /// <summary>
        /// Will accumulate data as it's received
        /// </summary>
        private string DataBuffer { get; set; }

        /// <summary>
        /// Store time of last data receipt. Need this in order to purge data after delay
        /// </summary>
        private DateTime LastDataReceivedOn { get; set; }

        #endregion

        public BaseTCPSocketListener()
        {
            // Preset all entries
            this.LastDataReceivedOn = DateTime.UtcNow;
            this.DataBuffer = string.Empty;

        }

        public void Init(string config)
        {
            // Parse info
            var bits = config.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            this.host = bits[0];
            var hostBytes = this.host.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            var hostIp = new IPAddress(new[] { byte.Parse(hostBytes[0]), byte.Parse(hostBytes[1]), byte.Parse(hostBytes[2]), byte.Parse(hostBytes[3]) });
            this.port = int.Parse(bits[1]);
            this.delayToClearBufferSeconds = int.Parse(bits[2]);

            // Close open client
            if (this.client?.Client != null)
            {
                this.client.Client.Disconnect(true);
                this.client = null;
            }

            // Connect to client
            this.client = new TcpClient();
            if (!this.client.ConnectAsync(hostIp, this.port).Wait(2500))
                throw new Exception($"Failed to connect to {this.host}:{this.port} in allotted time");

            this.EstablishReceiver();
        }

        protected void DataReceived(IAsyncResult result)
        {
            // End the data receiving that the socket has done and get the number of bytes read.
            var bytesCount = 0;
            try
            {
                bytesCount = this.client.Client.EndReceive(result);
            }
            catch (Exception ex)
            {
                this.RaiseOnErrorToClient(new Exception(nameof(this.DataReceived)));
                this.RaiseOnErrorToClient(ex);
            }

            // No data received, establish receiver and return
            if (bytesCount == 0)
            {
                this.EstablishReceiver();
                return;
            }

            // Convert the data we have to a string.
            this.DataBuffer += Encoding.UTF8.GetString(this.buffer, 0, bytesCount);

            // Record last time data received
            this.LastDataReceivedOn = DateTime.UtcNow;
            this.RaiseOnDataReceivedToClient(this.DataBuffer);

            this.DataBuffer = string.Empty;
            this.EstablishReceiver();
        }

        private void EstablishReceiver()
        {
            try
            {
                // Set up again to get the next chunk of data.
                this.client.Client.BeginReceive(this.buffer, 0, this.buffer.Length, SocketFlags.None, this.DataReceived, this.buffer);
            }
            catch (Exception ex)
            {
                this.RaiseOnErrorToClient(new Exception(nameof(this.EstablishReceiver)));
                this.RaiseOnErrorToClient(ex);
            }
        }

        private void RaiseOnErrorToClient(Exception ex)
        {
            if (this.OnError == null) return;

            foreach (Delegate d in this.OnError.GetInvocationList())
            {
                var syncer = d.Target as ISynchronizeInvoke;
                if (syncer == null)
                {
                    d.DynamicInvoke(this, ex);
                }
                else
                {
                    syncer.BeginInvoke(d, new object[] { this, ex });
                }
            }
        }

        private void RaiseOnDataReceivedToClient(string data)
        {
            if (this.OnDataReceived == null) return;

            foreach (Delegate d in this.OnDataReceived.GetInvocationList())
            {
                var syncer = d.Target as ISynchronizeInvoke;
                if (syncer == null)
                {
                    d.DynamicInvoke(this, data);
                }
                else
                {
                    syncer.BeginInvoke(d, new object[] { this, data });
                }
            }
        }
    }
}

客户端代码(在按钮上单击表单)

private void ListenBaseButton_Click(object sender, EventArgs e)
        {
            if (this.bsl == null)
            {
                this.bsl = new BaseTCPSocketListener();
                this.bsl.OnDataReceived += delegate (object o, string s)
                {
                    this.DataTextBox.Text += $"Base: {DateTime.Now} - {s}" + Environment.NewLine;
                };

                this.bsl.OnError += delegate (object o, Exception x)
                {
                    this.DataTextBox.Text += $"Base TCP receiver error: {DateTime.Now} - {x.Message}" + Environment.NewLine;
                };
            }

            try
            {
                this.bsl.Init("192.168.33.70|10001|10");
                this.DataTextBox.Text += "BEGIN RECEIVING BSL data --------------------------" + Environment.NewLine;
            }
            catch (Exception exception)
            {
                this.DataTextBox.Text += $"ERROR CONNECTING TO BSL ------------{exception.Message}" + Environment.NewLine;
            }
        }

我得到的例外情况。从DataReceived

中的处理程序第二次点击按钮时的第一个例外
  

未从相应的对象返回IAsyncResult对象   这个类的异步方法。

点击后,我从EstablishReceiver

中的处理程序获得异常
  

由于套接字是,因此不允许发送或接收数据的请求   未连接和(使用sendto在数据报套接字上发送时)   电话)没有提供地址

如何正确确保套接字关闭并重新打开?

3 个答案:

答案 0 :(得分:1)

  

未从相应的对象返回IAsyncResult对象   这个类的异步方法。

这是在前一个套接字调用数据回调(DataReceived())时发生的众所周知的问题。在这种情况下,您将使用不正确的Socket.EndReceive()实例调用IAsyncResult,该实例会抛出异常。

Asynchronous Client Socket Example包含此问题的可能解决方法:在状态对象中调用BeginReceive()的存储套接字,然后传递给DataReceived回调:

StateObject类

public class StateObject
{
    public Socket Socket { get; set; }

    public byte[] Buffer { get; } = new byte[1024];

    public StateObject(Socket socket)
    {
        Socket = socket;
    }
}

EstablishReceiver()方法:

private void EstablishReceiver()
{
    try
    {
        var state = new StateObject(client.Client);
        // Set up again to get the next chunk of data.
        this.client.Client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, this.DataReceived, state);
    }
    catch (Exception ex)
    {
        this.RaiseOnErrorToClient(new Exception(nameof(this.EstablishReceiver)));
        this.RaiseOnErrorToClient(ex);
    }
}

DataReceived()方法:

protected void DataReceived(IAsyncResult result)
{
    var state = (StateObject) result.AsyncState;

    // End the data receiving that the socket has done and get the number of bytes read.
    var bytesCount = 0;

    try
    {
        SocketError errorCode;
        bytesCount = state.Socket.EndReceive(result, out errorCode);
        if (errorCode != SocketError.Success)
        {
            bytesCount = 0;
        }
    }
    catch (Exception ex)
    {
        this.RaiseOnErrorToClient(new Exception(nameof(this.DataReceived)));
        this.RaiseOnErrorToClient(ex);
    }

    if (bytesCount > 0)
    {
        // Convert the data we have to a string.
        this.DataBuffer += Encoding.UTF8.GetString(state.Buffer, 0, bytesCount);

        // Record last time data received
        this.LastDataReceivedOn = DateTime.UtcNow;
        this.RaiseOnDataReceivedToClient(this.DataBuffer);

        this.DataBuffer = string.Empty;
        this.EstablishReceiver();
    }
}
  

由于套接字是,因此不允许发送或接收数据的请求   未连接和(使用sendto在数据报套接字上发送时)   电话)没有提供地址

以上DataReceived()方法还包含第二个异常的修复程序。在断开连接的套接字上调用BeginReceive()(来自EstablishReceiver())会导致异常。如果先前的读取带来了0个字节,则不应在套接字上调用BeginReceive()

答案 1 :(得分:0)

首先,您正在关闭TcpClient持有的套接字,但不会丢弃客户端本身。请尝试以下方法:

// Close open client
this.client?.Close();   // Disposes and releases resources
this.client = null;

答案 2 :(得分:0)

问题是关闭客户端时将调用DataReceived。你只需要确定方法不应该做任何事情,因为你故意结束了这个过程。你可以添加一个bool:

    private bool ignoreCallback;
    public void Init(string config)
    {
        // Parse info
        var bits = config.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
        this.host = bits[0];
        var hostBytes = this.host.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        var hostIp = new IPAddress(new[] { byte.Parse(hostBytes[0]), byte.Parse(hostBytes[1]), byte.Parse(hostBytes[2]), byte.Parse(hostBytes[3]) });
        this.port = int.Parse(bits[1]);
        this.delayToClearBufferSeconds = int.Parse(bits[2]);

        // Close open client
        if (this.client?.Client != null)
        {
            ignoreCallback = true;
            this.client.Client.Disconnect(true);
            this.client = null;
        }

        // Connect to client
        this.client = new TcpClient();
        if (!this.client.ConnectAsync(hostIp, this.port).Wait(2500))
            throw new Exception($"Failed to connect to {this.host}:{this.port} in allotted time");

        this.EstablishReceiver();
    }

    protected void DataReceived(IAsyncResult result)
    {
        if (ignoreCallback)
        {
            ignoreCallback = false;
            return;
        }

        ...