简体   繁体   English

如何使用C#通过TCP连接一次从多个客户端接收文件?

[英]How to receive file from multiple client at a time over TCP connection using C#?

I am having a server and multiple clients in my project. 我的项目中有一个服务器和多个客户端。 Server need to send the files by request, and it store the files from clients. 服务器需要根据请求发送文件,并存储来自客户端的文件。 I have coding, that connects with multiple clients but receives one file at time. 我有编码,可以连接多个客户端,但一次只能接收一个文件。 Other file store requests will proceed after the previous file received completely. 其他文件存储请求将在完全接收到前一个文件后继续进行。

My files size is around 200 MB. 我的文件大小约为200 MB。 So it takes more time to respond all clients. 因此,需要更多时间来响应所有客户。 How i will solve this. 我将如何解决这个问题。 Any one help me. 任何人都可以帮助我。 Thanks in advance. 提前致谢。

public partial class Form1 : Form
{
    byte[] Echo;
    byte[] a;
    Thread t1;
    int flag = 0;
    string receivedPath = "yok";
    public delegate void MyDelegate();
    private string fileName;
    public Form1()
    {
        t1 = new Thread(new ThreadStart(StartListening));
        t1.Start();
        InitializeComponent();
    }

    delegate void SetTextCallback(string text);

    public class StateObject
    {
        // Client socket.
        public Socket workSocket = null;

        public const int BufferSize = 8069;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
    }

    public static ManualResetEvent allDone = new ManualResetEvent(true);

    public void StartListening()
    {

        StateObject state = new StateObject();
        byte[] bytes = new Byte[8069];
        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 9050);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            listener.Bind(ipEnd);
            listener.Listen(100);
            while (true)
            {
                allDone.Reset();
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();

            }
        }
        catch (Exception ex)
        {
            SetText(ex.ToString());
        }

    }

    public void AcceptCallback(IAsyncResult ar)
    {

        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), state);
        flag = 0;


    }

    public void ReadCallback(IAsyncResult ar)
    {
        int fileNameLen = 1;
        String content = String.Empty;
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;
        try
        {
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {

                if (flag == 0)
                {

                    fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                    fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                    receivedPath = @"D:\" + fileName;
                    flag++;

                }

                if (flag >= 1)
                {
                    BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                    if (flag == 1)
                    {
                        writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                        flag++;
                    }
                    else
                    writer.Write(state.buffer, 0, bytesRead);
                    writer.Close();
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), state);
                }
            }
            else
            {

                allDone.Set();
                Invoke(new MyDelegate(LabelWriter));
            }
        }
       catch
        {
        }
    }
    public void LabelWriter()
    {
        label1.Text = "Data has been received " + fileName;
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        t1.Abort();
    }


}

You can trigger your allDone event within the AcceptCallback method. 您可以在AcceptCallback方法中触发allDone事件。 Immidiatly after accepting a client, you can spin of a process that is communicating with that client while in the meantime start listening for the next client. 接受客户端后,您可以旋转与该客户端进行通信的进程,同时开始监听下一个客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM