将字节流文件写入服务器,使用c#中的流将文件从服务器传输到客户端时数据丢失...

服务器端

stream.BeginWrite(clientData, 0, clientData.Length,

new AsyncCallback(CompleteWrite), stream);

客户端

int tot = s.Read(clientData, 0, clientData.Length);

我使用过TCPClient,TCPlistener类

clientData是一个字节数组。在服务器端,ClientData的大小为2682.I使用了NetworkStream类来写入数据

但在客户端,接收的数据只包含1642个字节。我使用流类来读取客户端的数据

怎么了?

答案

允许Read方法返回的字节数少于您请求的字节数。您需要重复调​​用Read,直到收到所需的字节数。

另一答案

使用此方法从流中正确读取:

public static void ReadWholeArray (Stream stream, byte[] data)

{

int offset=0;

int remaining = data.Length;

while (remaining > 0)

{

int read = stream.Read(data, offset, remaining);

if (read <= 0)

throw new EndOfStreamException

(String.Format("End of stream reached with {0} bytes left to read", remaining));

remaining -= read;

offset += read;

}

}

您可能希望首先将文件的长度写入流中(例如,作为int),例如,

服务器端:

server.Write(clientData.Length)

server.Write(clientData);

客户端:

byte[] size = new byte[4];

ReadWholeArray(stream, size);

int fileSize = BitConverter.ToInt32(size, 0);

byte[] fileBytes = new byte[fileSize];

ReadWholeArray(stream, fileBytes);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值