使用TcpClient和Tcplistener同时发送和接收多个文件

时间:2012-03-31 20:19:57

标签: c# multithreading tcpclient tcplistener

我正在尝试构建一个Server \ Client程序,它允许我在笔记本电脑和家用电脑之间同时传输多个文件。 发送单个文件时我的程序运行正常;但是,当我尝试在不同的线程上同时发送多个文件时,它不起作用(我在服务器上没有收到任何文件)

这就是我做的事情

foreach (string file in FilesCollection)
{
    Thread Thr = new Thread(ParameterizedThreadStart(Send));
    Thr.Start(file);
}

这是发送部分

    private void Send(string location)
    {
        TcpClient MyClient = null;
        FileStream MyFileStream = null;
        byte[] MyBuffer = null;
        int dSize = 0;
        try
        {
            MyClient = new TcpClient("127.0.0.1", 5555);
            MyFileStream = new FileStream(location, FileMode.Open, FileAccess.Read);
            MyBuffer = new byte[1024];
            Console.WriteLine("Transfering Data...");
            while (true)
            {
                try
                {
                    dSize = MyFileStream.Read(MyBuffer, 0, MyBuffer.Length);
                    MyClient.GetStream().Write(MyBuffer, 0, dSize);
                    if (dSize == 0)
                        break;
                }
                catch (Exception er)
                {
                    Console.WriteLine(er.Message);
                }
            }
            MyFileStream.Close();
            MyClient.Close();
            MyBuffer = null;
            Console.WriteLine("Transfer Complete");
        }
        catch (Exception er)
        {
            Console.WriteLine(er.Message);
        }
   }

这是接收部分

private void Receive(string location)
{
    TcpClient MyClient = null;
    FileStream MyFileStream = null;
    byte[] MyBuffer = null;
    int dSize = 0;
    try
    {
        MyClient = MyListener.AcceptTcpClient();
        Console.WriteLine("Connection Made");
        MyFileStream = new FileStream(location, FileMode.Create, FileAccess.Write);
        MyBuffer = new byte[4096];
        while (true)
        {
            dSize = MyClient.GetStream().Read(MyBuffer, 0, MyBuffer.Length);
            MyFileStream.Write(MyBuffer, 0, dSize);
            if (dSize == 0)
                break;
        }
        MyFileStream.Close();
        MyClient.Close();
        MyBuffer = null;
        Console.WriteLine("Transfer Complete");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

有人可以告诉我有什么问题,而且对于客户端,我是否必须启动tcplistner才能从服务器接收文件?

提前谢谢。

0 个答案:

没有答案