NetworkStream Read()太慢,需要约9分钟才能获得7.5 MB

时间:2019-05-19 15:12:20

标签: c# tcpclient networkstream

我有一些代码,可以使用TcpClient发送文件数据,但这太慢了。

  1. 发送10个字节的样本数据,数据将按预期发送和接收。
  2. 仅发送几MB的文件就需要很长时间

    public static void SendBytes(TcpClient clientSocket, byte[] outStream)
    {
        Debug.WriteLine("SendBytes() number of bytes: " + outStream.Length.ToString());
    
        byte[] encoded_outStream = EncoderDecoder.Encoder(outStream);
    
        NetworkStream serverStream = clientSocket.GetStream();
    
        byte[] rv = new byte[encoded_outStream.Length + ProgramState.end_networkdata_bytes.Length];
    
        System.Buffer.BlockCopy(encoded_outStream, 0, rv, 0, encoded_outStream.Length);
        System.Buffer.BlockCopy(ProgramState.end_networkdata_bytes, 0, rv, encoded_outStream.Length, ProgramState.end_networkdata_bytes.Length);
    
        serverStream.Write(rv, 0, rv.Length);
        serverStream.Flush();
    }
    
    private static int MAX_SIZE = 500000000;
    public static byte[] ReceiveBytes(TcpClient clientSocket)
    {
        Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes() started.");
        clientSocket.NoDelay = true;
        NetworkStream networkStream = clientSocket.GetStream();
    
        byte[] bytesFrom = new byte[MAX_SIZE];
        clientSocket.ReceiveBufferSize = MAX_SIZE;
    
        networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
    
        int index = GetFirstOccurance(ProgramState.end_networkdata_bytes[0], bytesFrom);
        Debug.WriteLine("ReceiveBytes(), SubArray index: " + index.ToString());
    
        byte[] tmp_res = bytesFrom.SubArray(0, index);
        byte[] res = EncoderDecoder.Decoder(tmp_res);
    
        Debug.WriteLine("ReceiveBytes() number of bytes: " + res.Length.ToString());
        return res;
    }
    

编辑:用于接收多个数据块的代码

    private static int MAX_SIZE = 10000;
    public static byte[] ReceiveBytes(TcpClient clientSocket)
    {
        Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes() started.");
        clientSocket.NoDelay = true;

        NetworkStream networkStream = clientSocket.GetStream();

        clientSocket.ReceiveBufferSize = MAX_SIZE;

        byte[] tmp_bytesFrom = new byte[MAX_SIZE];


        while(GetFirstOccurance(ProgramState.end_networkdata_bytes[0], tmp_bytesFrom) < 0)
        {
            networkStream.Read(tmp_bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
        }

        Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes(), received number of raw bytes: " + tmp_bytesFrom.Length.ToString());
        return tmp_bytesFrom;
    }

在发送几个MB(7.5 MB)的文件时,ReceiveBytes()函数大约需要9分钟。 注意: 1. Encoder()和Decoder()函数不会影响我的速度。 2.减小缓冲区大小不会使接收速度更快。 (已测试)。

0 个答案:

没有答案