从服务器向客户端C#发送多个文件

时间:2016-06-25 05:38:18

标签: c# file sockets server client

当我从客户端向服务器发送特定单词时,我需要从服务器向客户端发送多个文件,它对我有用,但现在我添加了更多代码,以便在服务器脱机时重新连接客户端 我需要的: 1)发送和接收大的多个文件 2)服务器关闭时重新连接 3)清理我的代码

客户端

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;

  namespace Multi_Client
  {
    class Program
    {
     private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     private const int _PORT = 1191;

    static void Main()
    {
        Console.Title = "Client";
        ConnectToServer();
        RequestLoop();
        Exit();
    }

    private static void ConnectToServer()
    {
        int attempts = 0;

        while (!_clientSocket.Connected)
        {
            try
            {
                attempts++;
                Console.WriteLine("Connection attempt " + attempts);
                 _clientSocket.Connect(IPAddress.Loopback, _PORT);
            }
            catch (SocketException) 
            {
                Console.Clear();
            }
        }

        Console.Clear();
        Console.WriteLine("Connected");
    }

    private static void RequestLoop()
    {
        Console.WriteLine(@"<Type ""exit"" to properly disconnect client>");

        while (true)
        {
            SendRequest();
            ReceiveResponse();
        }
    }

    /// <summary>
    /// Close socket and exit app
    /// </summary>
    private static void Exit()
    {
        SendString("exit"); // Tell the server we re exiting
        _clientSocket.Shutdown(SocketShutdown.Both);
        _clientSocket.Close();
        Environment.Exit(0);
    }

    private static void SendRequest()
    {
        Console.Write("Send a request: ");
        string request = Console.ReadLine();

        if (request.ToLower() == "exit")
        {
            Exit();
        }
        else if (request == "get time")
        {
            SendString(request);
        }
        else if (request.Contains("update")) //update + 188
        {
            SendString(request);
        }
    }

    /// <summary>
    /// Sends a string to the server with ASCII encoding
    /// </summary>
    public static string Text;
    private static void SendString(string text)
    {
        Text = text;
        try
        {
            byte[] buffer = Encoding.ASCII.GetBytes(text);
            _clientSocket.Send(buffer, 0, buffer.Length, SocketFlags.None);
        }
        catch
        {
            s1:
            try
            {
                _clientSocket.Shutdown(SocketShutdown.Both);
                _clientSocket.Close();
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.Connect(IPAddress.Loopback, _PORT);
                SendString(Text);
            }
            catch
            {
                try
                {
                    _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    _clientSocket.Connect(IPAddress.Loopback, _PORT);
                    SendString(Text);
                }
                catch
                {
                    goto s1;
                }
            }
        }
    }

    public static int FileNo = 1;
    private static void ReceiveResponse()
    {
        try
        {
            var buffer = new byte[99999999];
            int received = _clientSocket.Receive(buffer, SocketFlags.None);
            if (received == 0) return;

            var data = new byte[received];
            Array.Copy(buffer, data, received);
            int filePathLen = BitConverter.ToInt32(data, 0);
            int fileNumbers = BitConverter.ToInt32(data, 1);

            if (filePathLen != 0)
            {
                string filePath = Encoding.ASCII.GetString(data, 12, filePathLen);
                Console.WriteLine(filePath);
                string[] folderPath = filePath.Split(new string[] { "\\" }, StringSplitOptions.None);
                string[] folderPath2 = filePath.Split(new string[] { folderPath[folderPath.Length - 1] }, StringSplitOptions.None);
                if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + folderPath2[0]))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + folderPath2[0]);
                }
                FileStream Fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + filePath, FileMode.Create, FileAccess.Write);

                    Fs.Write(data, 12 + filePathLen, received - 12 - filePathLen);
                    Fs.Close();

                if (FileNo < fileNumbers)
                {
                    FileNo++;
                    ReceiveResponse();

                    _clientSocket.Shutdown(SocketShutdown.Both);
                    _clientSocket.Close();
                    SendString("reconnect");
                }
                else
                {
                    FileNo = 1;
                }
            }
            else
            {
                string text = Encoding.ASCII.GetString(data, 4, received - 4);
                Console.WriteLine(text);
            }


        }
        catch { }
    }
  }
}

服务器

            string text = Encoding.ASCII.GetString(recBuf);

            if (text.ToLower() == "get time") // Client requested time
            {
                Console.WriteLine("Text is a get time request");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
                byte[] NoUpdate = BitConverter.GetBytes(0);
                byte[] Data = new byte[NoUpdate.Length + data.Length];

                NoUpdate.CopyTo(Data, 0);
                data.CopyTo(Data, 0 + NoUpdate.Length);

                current.Send(Data);
                }
            else if (text.Contains("update"))
            {
                string[] getVersion = text.Split(new string[] { "-" }, StringSplitOptions.None);
                int version = Convert.ToInt32(getVersion[1]);

                string[] getUpdateNumVersions = Directory.GetDirectories(@"C:\Users\ahmed\Desktop\Update\");

                for (int a = 0; a < getUpdateNumVersions.Length; a++)
                {
                    string[] versionNum = getUpdateNumVersions[a].Split(new string[] { "\\" }, StringSplitOptions.None);

                    if (version < Convert.ToInt32(versionNum[versionNum.Length - 1]))
                    {
                        string[] foldersPaths = Directory.GetDirectories(getUpdateNumVersions[a], "*.*", SearchOption.AllDirectories);

                        for (int i = 0; i < foldersPaths.Length; i++)
                        {
                            string[] filePaths = Directory.GetFiles(foldersPaths[i]);
                            for (int j = 0; j < filePaths.Length; j++)
                            {
                                string[] getUpdatePath = filePaths[j].Split(new string[] { versionNum[versionNum.Length - 1] + "\\" }, StringSplitOptions.None);
                                string updatePath = getUpdatePath[1];

                                byte[] updatePathByte = Encoding.ASCII.GetBytes(updatePath);
                                byte[] updatePathLen = BitConverter.GetBytes(updatePath.Length);
                                byte[] fileNumbers = BitConverter.GetBytes(foldersPaths.Length);

                                byte[] fileData = File.ReadAllBytes(filePaths[j]);

                                byte[] Data = new byte[12 + updatePathByte.Length + fileData.Length];

                                updatePathLen.CopyTo(Data, 0);
                                fileNumbers.CopyTo(Data, 0 + updatePathLen.Length);
                                updatePathByte.CopyTo(Data, 12);

                                fileData.CopyTo(Data, 12 + updatePathByte.Length);

                                current.Send(Data);
                            }
                        }
                    }

0 个答案:

没有答案