4

为了涉足网络编程,我编写了一个小控制台应用程序来将 png 文件发送到服务器(另一个控制台应用程序)。服务器正在写入的文件比源 png 文件略大。它不会打开。

客户端应用程序的代码是:

    private static void SendFile()
    {
        using (TcpClient tcpClient = new TcpClient("localhost", 6576))
        {
            using (NetworkStream networkStream = tcpClient.GetStream())
            {
                //FileStream fileStream = File.Open(@"E:\carry on baggage.PNG", FileMode.Open);

                byte[] dataToSend = File.ReadAllBytes(@"E:\carry on baggage.PNG");

                networkStream.Write(dataToSend, 0, dataToSend.Length);
                networkStream.Flush();

            }
        }

    }

服务器应用程序的代码是:

    private static void Main(string[] args)
    {
        Thread thread = new Thread(new ThreadStart(Listen));
        thread.Start();

        Console.WriteLine("Listening...");
        Console.ReadLine();
    }

    private static void Listen()
    {
        IPAddress localAddress = IPAddress.Parse("127.0.0.1");
        int port = 6576;
        TcpListener tcpListener = new TcpListener(localAddress, port);
        tcpListener.Start();

        using (TcpClient tcpClient = tcpListener.AcceptTcpClient())
        {
            using (NetworkStream networkStream = tcpClient.GetStream())
            {
                using (Stream stream = new FileStream(@"D:\carry on baggage.PNG", FileMode.Create, FileAccess.ReadWrite))
                {
                    // Buffer for reading data
                    Byte[] bytes = new Byte[1024];
                    var data = new List<byte>();

                    int length;

                    while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        var copy = new byte[length];
                        Array.Copy(bytes, 0, copy, 0, length);
                        data.AddRange(copy);
                    }

                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    stream.Position = 0;
                    binaryFormatter.Serialize(stream, data.ToArray());
                }
            }

        }
        tcpListener.Stop();

写入文件的大小为 24,103Kb,而源文件只有 24,079Kb。

任何人都清楚为什么此操作失败了吗?

干杯

4

1 回答 1

5

您正在使用 BinaryFormatter 编写输出。我很确定这将在输出的开头添加一些字节以指示您正在输出的类型(在本例中为 System.Byte [])。
只需将字节直接写入文件而不使用格式化程序:

using (Stream stream = new FileStream(@"D:\carry on baggage.PNG", FileMode.Create, FileAccess.ReadWrite))
{
    // Buffer for reading data
    Byte[] bytes = new Byte[1024];

    int length;

    while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0)
    {
        stream.Write(bytes, 0, length);
    }
}
于 2012-07-09T14:15:51.817 回答