none
TcpListener在Windows Form使用NetworkStream 接收檔案錯誤 RRS feed

  • 問題

  • 請問一下我寫了一個TcpListener來接收遠端傳來的檔案,一開始我先用主控台程式寫,
    參照了msdn上的範例,程式碼如下:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Data;
    
    namespace TcpListenerTest
    {
        class MyTcpListener
        {
            public static void Main()
            {
                TcpListener server = null;
                try
                {
    
                    String input;
                    Console.WriteLine("請輸入要監聽的 IP");
                    input = Console.ReadLine();
    
                    IPAddress localAddr = IPAddress.Parse(input);
                    Int32 port = 80;
    
                    server = new TcpListener(localAddr, port);
                    server.Start();
    
                    Byte[] bytes = new Byte[256];
                    String data = null;
    
                    // Enter the listening loop.
                    while (true)
                    {
                        Console.Write("Waiting for a connection... ");
    
                        TcpClient client = server.AcceptTcpClient();
                        
                        Console.WriteLine("Connected!");
    
                        data = null;
    
                        NetworkStream stream = client.GetStream();
    
                        string path = @"c:\test.txt";
                        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                        StreamWriter sw = new StreamWriter(fs, UnicodeEncoding.Unicode);
                        
                        int i;
    
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            data = System.Text.UnicodeEncoding.Unicode.GetString(bytes, 0, i);
                            Console.WriteLine("Received: {0}", data);
                            sw.Write(data);
    
                        }
                    
                        sw.Close();
                        fs.Close();
                        stream.Close();
                        client.Close();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
                finally
                {
                    server.Stop();
                }
                Console.WriteLine("\nHit enter to continue...");
                Console.Read();
            }
        }
    }
    這個主控台程式可以順利讀取遠端傳來的檔案,完全沒有問題...
    可是後來我把這個程式寫成Windows Form後,
    在接收檔案時,常常會出現接收到的檔案打開發現檔案前幾行都變成亂碼了,
    每次變成亂碼的行數不太固定,不過都是只有前幾行,後面幾行會正常,
    少數有幾次會成功接收沒有出現亂碼
    程式碼如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace TcpListenerForm
    {
        public partial class Form1 : Form
        {
            String Addr = null;
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                textBox2.ScrollBars = ScrollBars.Both;
                Form1.CheckForIllegalCrossThreadCalls = false;
                textBox2.Text += "請輸入要監聽的IP : .........\r\n";
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
     
                Addr = Convert.ToString(textBox1.Text);
    
                if (Addr == null)
                    MessageBox.Show("你還沒輸入IP!!\r\n");
                else
                {
                    Thread run = new Thread(new ThreadStart(StartListen));
                    run.Name = "runlisten";
                    run.Start();
                }
            }
    
            public void StartListen()
            {
                TcpListener server = null;
    
                try
                {
                    Int32 port = 80;
                    IPAddress localAddr = IPAddress.Parse(Addr);
    
                    server = new TcpListener(localAddr, port);
                    server.Start();
    
                    Byte[] bytes = new Byte[256];
                    String data = null;
    
                    while (true)
                    {
                        textBox2.Text += "\r\n\r\nWaiting for a connection...\r\n\r\n";
    
                        TcpClient client = server.AcceptTcpClient();
    
                        textBox2.Text += "\r\n\r\nConnected!\r\n\r\n";
     
                        NetworkStream stream = client.GetStream();
    
                        data = null;
    
                        String path = @"c:\test.txt";
                        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                        StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
    
                        int i;
    
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            data = System.Text.UnicodeEncoding.Unicode.GetString(bytes, 0, i);
                            textBox2.Text += "Received:" + data + "\r\n";
                            sw.Write(data);
                        }
    
                        // Shutdown and end connection
                        sw.Close();
                        fs.Close();
                        stream.Close();
                        client.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    server.Stop();
                }
    
            }
    
        }
    }

    想請問我Windows Form的程式問題出在哪,該怎麼修該才好呢?

    • 已編輯 Ozlinbo 2009年8月14日 下午 03:07
    2009年8月14日 下午 03:00

解答

  • data = System.Text.UnicodeEncoding.Unicode.GetString(bytes, 0, i);

    你覺這的這行來說,接到的位元組數,會剛好斷在每個字的完結之處嗎?要是 i 是奇數後面會變怎樣,想完答案就出來了。


    論壇是網友平等互助 保證解答請至 微軟技術支援服務
    • 已標示為解答 Lolota Lee 2009年8月21日 上午 05:30
    2009年8月14日 下午 04:40