使用NetworkStream传输文件

时间:2010-09-07 23:02:56

标签: c# .net .net-3.5 c#-3.0 networkstream

我无法从服务器程序将文件传输到客户端。我想解决一些问题。首先是我使字节数组大6000字节,并且它总是那么大。有没有办法保持正确的文件大小?此外,代码现在的方式,程序挂起。它在我从客户端的while循环中取出时起作用。帮助!

客户端:

 private void button1_Click(object sender, EventArgs e)
    {   
        BinaryWriter binWriter; 
        int i = -1;
        Byte[] bytes = new Byte[6000];

        NetworkStream clientStream = connTemp.GetStream();
        byte[] outstream = Encoding.ASCII.GetBytes(txtMessage.Text);
        clientStream.Write(outstream, 0, outstream.Length);


        while (i != 0)
        {
            try
            {
                if (clientStream.CanRead)
                {
                    i = clientStream.Read(bytes, 0, bytes.Length);

                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                break;
            }
        }


        binWriter = new BinaryWriter(File.Open("C:\\SeanLaunch\\log.rxlog",FileMode.Create));
        binWriter.Write(bytes);
        binWriter.Close();

    }

}

服务器:

  Byte[] fileToSendAsByteArray = new Byte[6000];
  fileToSendAsByteArray = File.ReadAllBytes("C:\\Launch\\Test.rxlog");
  stream.Write(fileToSendAsByteArray, 0, fileToSendAsByteArray.Length);

编辑!!!:我修复了循环问题。

2 个答案:

答案 0 :(得分:2)

一个问题是,即使您只读取文件中的一个字节,也要将整个6000字节写入流中。

使用FileStream访问该文件并将内容复制到NetworkStream。 Framework 4.0有一个很好的功能

FileStream fs = new FileStream(...);
fs.CopyTo(stream);

您可以为客户端采取类似的方法,反过来,从NetworkStream复制到目标流。

在Framework 4.0之前,您可以实现自己的CopyTo功能。像这样的东西

public static long CopyStream(Stream source, Stream target)
{
  const int bufSize = 0x1000;
  byte[] buf = new byte[bufSize];

  long totalBytes = 0;
  int bytesRead = 0;

  while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
  {
    target.Write(buf, 0, bytesRead);
    totalBytes += bytesRead;
  }
  return totalBytes;
}

答案 1 :(得分:1)

如果CanRead在非零时仍为false,程序将永远循环。或者,它可能会在读取呼叫中被阻止。

调试您的接收方以了解正在发生的事情。它真的挂了,还是只是循环?

添加代码以转储在每端发送和接收的数据,以查看在问题出现之前您读取的确定程度。