【问题标题】:C# mixing the streamsC# 混合流
【发布时间】:2014-11-04 14:58:17
【问题描述】:

面临的问题:每 40 毫秒将相同的字节数组写入流。在无限循环中读取此线程。但是字节数组完全错误。这可能是混合流,有人遇到过这个问题吗?

写入字节数组:

public void HandleCommunication()
    {
        var dataBytes = new List<byte>();

        foreach (double value in _values)
        {
            dataBytes.AddRange(BitConverter.GetBytes(value));
        }

        _client.GetStream().Write(dataBytes.ToArray(), 0, dataBytes.Count);
        _client.GetStream().Flush();
    }

并读取字节数组:两次后字节数组出错。

public void GetData()
    {
        TcpClient client = _server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        while (true)
        {
            var stream = client.GetStream();
            Values = new double[2 * 16 * 1024];
            byte[] buffer = new byte[Values.Length * sizeof(double)];

            stream.Read(buffer, 0, buffer.Length);
            stream.Flush();               
        }

当我每 250 毫秒读取一次数据时,字节数组就正确了!

好的,更多细节: 我有一个带有数字的文本文件。我阅读并发送:

public partial class MainWindow : Window
{
    private double[] values;
    private System.Timers.Timer timer = new System.Timers.Timer(40);
    Client _client = new Client("127.0.0.1", 55443);


    public MainWindow()
    {
        InitializeComponent();
        OpenSrcFile();

        timer.Elapsed += TimerOnElapsed;
        timer.Enabled = true;
    }


    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        _client.SendValues(values);
    }


    public void OpenSrcFile()
    {
        List<string> lines = File.ReadAllLines(@"file.txt").ToList();
        string r = lines[0];
        int sizeX = int.Parse(lines[1]);
        lines.RemoveRange(0, 2);
        values = GetValues(lines.ToArray());
    }

}

客户端代码:

class Client
{ 
    private TcpClient _client;
    private Stream _stream;
    private double[] _values;


    public Client(String ipAddress, int portNum)
    {
        _client = new TcpClient() { SendBufferSize = 2 * 16 * 1024 * sizeof(double) };
        _client.Connect(ipAddress, portNum);
        _stream = _client.GetStream();
    }


    public void SendValues(double[] values)
    {
        _values = values;
        HandleCommunication();
    }


    public void HandleCommunication()
    {

        _isConnected = true;

        var dataBytes = new List<byte>();

        foreach (double value in _values)
        {
            dataBytes.AddRange(BitConverter.GetBytes(value));
        }

        NetworkStream newStream = _client.GetStream();
        _client.GetStream().Write(dataBytes.ToArray(), 0, dataBytes.Count);
        _client.GetStream().Flush();

    }

}

服务器然后接收这个字节数组,但我每次发送相同的数组。但是两次迭代后字节数组的接受程度不同! 服务器代码:

class Server
{
    private TcpListener _server;


    public Server(int port)
    {
        _server = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
        _server.Start();
    }

    public double[] Values { get; private set; }

    public delegate void DataUpdatedEventHandler(object sender, EventArgs args);

    public event DataUpdatedEventHandler DataUpdated;

    protected virtual void OnDataUpdated()
    {
        DataUpdatedEventHandler handler = DataUpdated;
        if (handler != null) handler(this, EventArgs.Empty);
    }


    public void GetData()
    {


        // wait for client connection

        TcpClient client = _server.AcceptTcpClient();

        Console.WriteLine("Connected!");



        while (true)
        {
            var stream = client.GetStream();

                Values = new double[2 * 16 * 1024];
                byte[] buffer = new byte[Values.Length * sizeof(double)];



                stream.Read(buffer, 0, buffer.Length); //wrong array of bytes!



                for (int i = 0; i < Values.Length; i++)
                {
                    Values[i] = BitConverter.ToDouble(buffer, i * sizeof(double));
                }



                OnDataUpdated();

        }
    }
}

我不明白这是什么...

【问题讨论】:

  • 检查Write()Read()的返回值。
  • 阅读时为什么Flush()
  • 这个问题太模糊了。请具体说明出了什么问题,清楚地说明您预期会发生什么,以及发生了什么。此外,您应该发布更完整的代码示例,准确显示您发送的数据。话虽如此,您的代码的一个主要问题是您忽略了stream.Read() 的返回值,因此如果您最初只收到发送的部分数据,您将永远不会发现。
  • 描述所有细节

标签: c# tcp stream byte


【解决方案1】:

看一下关于 TcpClient 类的 MS 文章: http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream%28v=vs.110%29.aspx

如您所见,.Net 中的流可以在字节上具有可变长度。 您应该通过以下方式获取数据:

  Encoding.UTF8.GetString (bytes);

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多