Stream.Read

using System;
using System.IO;

public class Block
{
    public static void Main()
    {
        Stream s = new MemoryStream();
        for (int i=0; i<100; i++)
            s.WriteByte((byte)i);
        s.Position = 0;

        // Now read s into a byte buffer.
        byte[] bytes = new byte[s.Length];
        int numBytesToRead = (int) s.Length;
        int numBytesRead = 0;
        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to numBytesToRead.
            int n = s.Read(bytes, numBytesRead, numBytesToRead);
            // The end of the file is reached.
            if (n==0)
                break;
            numBytesRead += n;
            numBytesToRead -= n;
        }
        s.Close();
        // numBytesToRead should be 0 now, and numBytesRead should
        // equal 100.
        Console.WriteLine("number of bytes read: "+numBytesRead);
    }
}

转载于:https://www.cnblogs.com/lcl_1015/articles/1657294.html

### 解决 C# 中 TcpClient 通过 ADB 进行 Stream.Read 无响应的问题 在使用 `TcpClient` 和 `NetworkStream` 处理 ADB 数据流时,可能会遇到 `stream.Read` 方法阻塞或无响应的情况。这通常是由于以下几个原因引起的:数据未完全接收、缺少终止标志或者网络延迟等问题[^1]。 #### 1. 确保命令正确结束 ADB 命令需要以 `\r\n` 结束,这是协议的标准要求。如果命令未按此格式发送,可能导致设备无法识别命令并返回结果。例如,在发送广播命令时,应确保如下形式: ```csharp byte[] sendBytes = Encoding.UTF8.GetBytes("shell am broadcast -a NotifyServiceStart\r\n"); ``` #### 2. 设置合理的缓冲区大小 默认情况下,`ReceiveBufferSize` 可能不足以容纳完整的响应数据。建议手动调整缓冲区大小以适应预期的最大响应长度。例如: ```csharp int bufferSize = 4096; // 自定义缓冲区大小 byte[] receiveBuffer = new byte[bufferSize]; ``` #### 3. 添加超时机制 为了避免无限期等待,应在读取操作前设置超时参数。可以通过以下方式实现: ```csharp client.SendTimeout = 5000; // 发送超时时间为 5 秒 client.ReceiveTimeout = 5000; // 接收超时时间为 5 秒 try { int bytesRead = stream.Read(receiveBuffer, 0, receiveBuffer.Length); string response = Encoding.UTF8.GetString(receiveBuffer, 0, bytesRead); Console.WriteLine($"Response from device:\n{response}"); } catch (SocketException ex) { Console.WriteLine($"A socket exception occurred: {ex.Message}"); } ``` #### 4. 判断是否有可读数据 在调用 `stream.Read` 之前,先检查是否存在待读取的数据。如果没有数据,则跳过当前循环继续尝试其他逻辑处理。 ```csharp if (!stream.DataAvailable || stream.CanRead == false) { Thread.Sleep(100); // 尝试短暂停顿后再重新评估状态 continue; } ``` #### 5. 考虑异步模式 对于长时间运行的任务,推荐改用异步 I/O 操作代替同步版本。这样不仅可以提高性能还能有效防止主线程被挂起。 ```csharp await Task.Run(async () => { while (true) { var result = await stream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length).ConfigureAwait(false); if(result > 0){ break; } } }); ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值