回写后从TcpClient接收无尽数据

时间:2019-05-22 12:44:28

标签: c# multithreading asynchronous tcp eventhandler

我正在使用WinForm项目连接到TcpClient,它每5秒向我发送一条消息。

为此,我创建了一个Thread并执行while(some condition)并通过NetworkStream读取数据,如果有数据,则会引发一些自定义EventHandler

在GUI上,我得到一个带有计时器的数据,该计时器每1秒滴答一次

虽然一切正常,但我可以毫无问题地进行数据记录。 但是之后,由于某种原因,我写回远程服务器的原因是无休止地以无比快的速度返回了无数数据,并且在我看来,我获取的数据已损坏。 / p>

我的客户班

public class mTcpClient 
{
    public mTcpClient()
    {
        StringEncoder = System.Text.Encoding.UTF8;
        ReadLoopIntervalMs = 10;

    }

    private Thread _rxThread = null;

    public System.Text.Encoding StringEncoder { get; set; }
    private TcpClient _client = null;
    private NetworkStream _networkStream = null;


    public event EventHandler<Message> DataReceived;

    internal bool QueueStop { get; set; }
    internal int ReadLoopIntervalMs { get; set; }
    public bool AutoTrimStrings { get; set; }

    public mTcpClient Connect(string hostNameOrIpAddress, int port)
    {
        if (string.IsNullOrEmpty(hostNameOrIpAddress))
        {
            throw new ArgumentNullException("hostNameOrIpAddress");
        }

        _client = new TcpClient();
         _client.Connect(hostNameOrIpAddress, port);
        _networkStream = _client.GetStream();

        StartRxThread();

        return this;
    }

    private void StartRxThread()
    {
        if (_rxThread != null) { return; }

        _rxThread = new Thread(ListenerLoop);
        _rxThread.IsBackground = true;
        _rxThread.Start();
    }

    public mTcpClient Disconnect()
    {
        if (_client == null) { return this; }
        _client.Close();
        _client = null;

        _networkStream.Close();
        _networkStream = null;

        QueueStop = true;

        return this;
    }

    public TcpClient TcpClient { get { return _client; } }

    private void ListenerLoop(object state)
    {
        while (!QueueStop)
        {
            try
            {
                RunLoopStep();
            }
            catch
            {
                // TODO
            }

           Thread.Sleep(ReadLoopIntervalMs);
        }

        _rxThread = null;
    }


    private void RunLoopStep()
    {
        if (_client == null) { return; }
        if (_client.Connected == false) { return; }   
        if (_client.Available == 0)
        {
            Thread.Sleep(ReadLoopIntervalMs);
            return;
        }

       var bytesReceived = new List<byte>();

        while (_client.Available > 0 && _client.Connected)
        {
            byte[] nextByte = new byte[1];
            _networkStream.Read(nextByte, 0, nextByte.Length);
            bytesReceived.AddRange(nextByte);            

        }

        if (bytesReceived.Count > 0)
        {
            NotifyEndTransmissionRx(_client, bytesReceived.ToArray());
        }
    }      

    private void NotifyEndTransmissionRx(TcpClient client, byte[] msg)
    {
        if (DataReceived != null)
        {
            Message m = new Message(msg, client, StringEncoder);
            DataReceived(this, m);

        }
    }

    public void  Write(string data)
    {
        if (data == null) { return; }
        if (_client == null) { throw new Exception("Cannot send data to a null TcpClient (check to see if Connect was called)"); }
        var encodedData = StringEncoder.GetBytes(data);
         _networkStream.Write(encodedData, 0, encodedData.Length);
         _networkStream.Flush();

    }

}

我的留言班

public class Message
{

    private TcpClient _tcpClient;
    private System.Text.Encoding _encoder = null;

    internal Message(byte[] data, TcpClient tcpClient, System.Text.Encoding stringEncoder)
    {
        Data = data;
        _tcpClient = tcpClient;
        _encoder = stringEncoder;         
    }

    public byte[] Data { get; private set; }
    public string MessageString
    {
        get
        {   
            return _encoder.GetString(Data);
        }
    }      

    public TcpClient TcpClient { get { return _tcpClient; } }
}

正常数据流,无回写 回写后数据流不正常

0 个答案:

没有答案