使用TcpClient和Tcplistner同时发送和接收多个文件 [英] Send and receive multiple files simultaneously using TcpClient and Tcplistner

查看:95
本文介绍了使用TcpClient和Tcplistner同时发送和接收多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我正在尝试构建一个Server \ Client程序,该程序允许我在笔记本电脑和家用计算机之间同时传输多个文件.我在一篇文章中发现,异步连接允许您执行此操作,因此,这是我到目前为止已完成的操作:

服务器

Hello,

I''m trying to build a Server\Client program which allows me to transfer multiple files simultaneously between my laptop and home computer. I found in an article that an asynchronous connection allows you to do that, so here''s what I''ve done so far:

The Server

namespace Server
{
    class ClientWrapper
    {
        private TcpClient MyClient = null;

        public delegate void Connect(byte[] data);
        public event Connect eConnect;

        public delegate void Error(string msg);
        public event Error eError;

        public ClientWrapper(TcpClient Client)
        {
            MyClient = Client;
            MyClient.GetStream().BeginRead(new byte[] { 0 }, 0, 0, new AsyncCallback(Read), null);
        }

        private void Read(IAsyncResult Arg)
        {
            byte[] MyChunk = new byte[4096];
            Int32 dSize = 0;
            try
            {
                while (true)
                {
                    dSize = MyClient.GetStream().Read(MyChunk, 0, MyChunk.Length);
                    eConnect(MyChunk);
                    if (dSize == 0)
                        break;
                }
                MyClient.GetStream().BeginRead(new byte[] { 0 }, 0, 0, new AsyncCallback(Read), null);
            }
            catch (Exception ex)
            {
                eError(ex.Message);
            }
        }

        public void Write(byte[] Data)
        {
            try
            {
                MyClient.GetStream().Write(Data, 0, Data.Length);
            }
            catch (Exception ex)
            {
                eError(ex.Message);
            }
        }

    }

    public partial class iServer : Form
    {
        public iServer()
        {
            InitializeComponent();
        }

        private void iServer_Load(object sender, EventArgs e)
        {
            Accept();
        }

        private TcpListener MyListner = null;
        private ClientWrapper MyClient = null;
        private bool Connected = false;

        private void Accept()
        {
            MyListner = new TcpListener(IPAddress.Any, 5555);
            MyListner.Start();
            MyListner.BeginAcceptTcpClient(new AsyncCallback(AcceptCallBack), MyListner);
        }

        private void AcceptCallBack(IAsyncResult Arg)
        {
            MyClient = new ClientWrapper(MyListner.EndAcceptTcpClient(Arg));
            MyClient.eConnect += new ClientWrapper.Connect(Read);
            MyClient.eError += new ClientWrapper.Error(Error);
            Connected = true;
            MyListner.BeginAcceptTcpClient(new AsyncCallback(AcceptCallBack), MyListner);
        }

        private void Error(string msg)
        {
            MessageBox.Show(msg, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void Read(byte[] MyChunk)
        {
            FileStream fs = new FileStream("MyFile.ext", FileMode.Append, FileAccess.Write);
            try
            {
                fs.Write(MyChunk, 0, MyChunk.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Write(byte[] MyBffer)
        {
            try
            {
                MyClient.Write(MyBffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SendFile_Click(object sender, EventArgs e)
        {
            if (!Connected)
                return;
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    byte[] Data = new byte[1024];
                    Int32 dSize = 0;
                    using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            while (true)
                            {
                                dSize = fs.Read(Data, 0, Data.Length);
                                Write(Data);
                                if (dSize == 0)
                                    break;
                            }
                            Data = null;
                            MessageBox.Show("done");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }

                }
            }
        }
    }
}   




客户




The Client

namespace Client
{
    public partial class iClient : Form
    {
        public iClient()
        {
            InitializeComponent();
            button1.Click += new EventHandler(Connect);
        }

        private TcpClient MyClient = null;
        
        private void Connect(object sender, EventArgs e)
        {
            try
            {
                MyClient = new TcpClient("127.0.0.1", 5555);
                MessageBox.Show("Connected");
                button1.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Read(IAsyncResult Arg)
        {
            FileStream fs = new FileStream("MyFile.ext", FileMode.Create, FileAccess.Write);
            byte[] MyChunk = new byte[4096];
            Int32 dSize = 0;
            try
            {
                while (true)
                {
                    dSize = MyClient.GetStream().Read(MyChunk, 0, MyChunk.Length);
                    fs.Write(MyChunk, 0, dSize);
                    if (dSize == 0)
                        break;
                }
                fs.Close();
                MyChunk = null;
                MyClient.GetStream().BeginRead(new byte[] { 0 }, 0, 0, new AsyncCallback(Read), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void Write(byte[] Data)
        {
            try
            {
                MyClient.GetStream().Write(Data, 0, Data.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SendFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    byte[] Data = new byte[1024];
                    Int32 dSize = 0;
                    using (FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            while (true)
                            {
                                dSize = fs.Read(Data, 0, Data.Length);
                                Write(Data);
                                if (dSize == 0)
                                    break;
                            }
                            Data = null;
                            MessageBox.Show("done");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }
        }
    }
}



好的,当我尝试将文件从服务器发送到客户端时,它不会发送文件.我知道我的代码有问题,但是我无法弄清楚,我想知道是否有人可以帮助我解决这个问题.



OK, when I try to send a file from the server to the client it doesn''t send it. I know that there''s something wrong with my code, but I can''t figure it out and I wonder if someone could help me with this.

thank you in advance.

推荐答案

您在服务器端的错误是使用同一线程接受新连接并使用网络流.由于您的服务器线程正忙于处理网络流,因此该模式无法工作,无法接受新的连接.实际上,您无法实现线程化的目的.服务器端至少需要两个网络线程来执行这两种不同的活动.

您可以在我过去的答案中找到更多详细信息:
来自同一端口号的多个客户端 [
Your mistake on the server side is using the same thread for accepting a new connection and working with a network stream. Such schema cannot work, because your server''s thread busy with working with a network stream is unable to accept new connection. Effectively, you defeat the purpose of threading. You need at least two network threads on the server side for these two different activity.

You can find further detail in my past answer:
Multple clients from same port Number[^].

—SA


这篇关于使用TcpClient和Tcplistner同时发送和接收多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆