C#Socket文件传输查询

Server端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace Server
{
    class Program
    {
        public static class soc
        {
            //创建一个socket
            public static Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        #region use different methods
        public static void accOrder()
        {
            while (true)
            {
                Console.WriteLine("Server is ready!");
                Socket cliSocket = soc.server.Accept();
                byte[] buf = new byte[BufSize];
                CommandType choice;
                //accept commands
                int tRead = cliSocket.Receive(buf);
                string command = Encoding.UTF8.GetString(buf, 0, tRead);
                string order = command.Substring(0, 4);
                order = order.ToLower();
                string filename;
                choice = deaOrder(order);
                filename = command.Substring(5);
                filename = filename.Trim();
                //choice
                if (choice == CommandType.Retrieve)
                    Retrieve(cliSocket, filename);
                else if (choice == CommandType.Store)
                    Store(cliSocket, filename);
                else if (choice == CommandType.Status)
                    Status(cliSocket, filename);
                else
                    Invalid(cliSocket);
            }
        }
        #endregion

        #region choose commands
        public static CommandType deaOrder(string order)
        {
            CommandType choice = 0;
            switch (order)
            {
                case "retr": choice = CommandType.Retrieve;
                    break;
                case "stor": choice = CommandType.Store;
                    break;
                case "stat": choice = CommandType.Status;
                    break;
                default: choice = CommandType.InvalidCommand;
                    break;
            }
            return choice;
        }
        #endregion

        #region download files
        public static void Retrieve(Socket clisocket, string filename)
        {
            FileStream SendFile = new FileStream(@filename, FileMode.Open, FileAccess.Read);
            try
            {
                byte[] sendBuf = new byte[BufSize];
                int fRead = 0;
                long tRead = 0;
                fRead = SendFile.Read(sendBuf, 0, sendBuf.Length);
                while (fRead > 0)
                {
                    clisocket.Send(sendBuf, fRead, SocketFlags.None);
                    tRead += fRead;
                    fRead = SendFile.Read(sendBuf, 0, sendBuf.Length);
                }
                Console.WriteLine("Sent {0} bytes!", tRead);
            }
            catch (Exception e)
            {
                Console.WriteLine("error: " + e.Message);
            }
            finally
            {
                SendFile.Close();
                clisocket.Close();
                //Console.ReadKey();
            }
        }
        #endregion

        #region upload files
        public static void Store(Socket clisocket, string filename)
        {
            filename = filename.Substring(3);
            filename = ".\\" + filename;
            FileStream RecFile = new FileStream(filename, FileMode.OpenOrCreate);
            int fRead;
            long tWrite = 0;
            try
            {
                byte[] buf = new byte[BufSize];
                fRead = clisocket.Receive(buf);
                while (fRead > 0)
                {
                    RecFile.Write(buf, 0, fRead);
                    tWrite += fRead;
                    fRead = clisocket.Receive(buf);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            Console.WriteLine("Received {0} bytes!", tWrite);
            RecFile.Close();
            clisocket.Close();
            Console.ReadKey();
        }
        #endregion

        #region files' length
        public static void Status(Socket clisocket, string filename)
        {
            string message;
            FileInfo fileInfo = new FileInfo(filename);
            if (!File.Exists(filename))
                message = "Sorry, the file does not exist!";
            else
                message = "The lengh of the file is " + fileInfo.Length + " bytes";
            clisocket.Send(Encoding.UTF8.GetBytes(message));
            Console.WriteLine("Information have sent");
        }
        #endregion

        #region invalid commands
        public static void Invalid(Socket clisocket)
        {
            string message = "Invalid command!";
            clisocket.Send(Encoding.UTF8.GetBytes(message));
            Console.WriteLine("Invalid command");
        }
        #endregion

        public enum CommandType { InvalidCommand, Retrieve, Store, Status };
        const int BufSize = 4096;

        static void Main(string[] args)
        {
            //bind a IPEndPoint
            soc.server.Bind(new IPEndPoint(IPAddress.Any, 23456));
            soc.server.Listen(100);
            Thread acc = new Thread(accOrder);
            acc.Start();
        }

    }
}
Client端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;


namespace Client
{
    class Program
    {
        const int BufSize = 4096;


        #region tips
        public static string ShowOrder()
        {
            for (int i = 0; i <= 79; i++)
                Console.Write('*');
            Console.WriteLine("You can use this client to check a file's length, or to upload or download a file");
            Console.WriteLine("Each command should follow this format: <ordername> <pathname> <CLRF>");
            Console.WriteLine("To download a file, enter \"retr\" and the file's name, to upload, enter \"stor\"");
            Console.WriteLine("And to check the file's length, enter \"stat\".");
            for (int i = 0; i <= 79; i++)
                Console.Write('*');
            Console.Write("Now enter your command(\"quit\" to quit):");
            string command = Console.ReadLine();
            return command;
        }
        #endregion

        #region download files
        public static void Retrieve(Socket client, string com, byte[] buf, string filename)
        {
            client.Send(Encoding.UTF8.GetBytes(com));
            filename = filename.Substring(3);
            filename = ".\\" + filename;
            FileStream RecFile = new FileStream(filename, FileMode.OpenOrCreate);
            int fRead;
            long tWrite = 0;
            try
            {
                fRead = client.Receive(buf);
                while (fRead > 0)
                {
                    RecFile.Write(buf, 0, fRead);
                    tWrite += fRead;
                    fRead = client.Receive(buf);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            Console.WriteLine("Received {0} bytes!", tWrite);
            RecFile.Close();
            client.Close();
        }
        #endregion

        #region upload files
        public static void Store(Socket client, string com, byte[] buf, string filename)
        {
            client.Send(Encoding.UTF8.GetBytes(com));
            FileStream SendFile = new FileStream(filename, FileMode.Open, FileAccess.Read);
            //尝试读取,发送
            try
            {
                int fRead = 0;
                long tRead = 0;
                fRead = SendFile.Read(buf, 0, buf.Length);
                while (fRead > 0)
                {
                    client.Send(buf, fRead, SocketFlags.None);
                    tRead += fRead;
                    fRead = SendFile.Read(buf, 0, buf.Length);
                }
                Console.WriteLine("You have sent {0} bytes!", tRead);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error " + e.Message);
            }
            //关闭文件流,关闭Socket
            finally
            {
                SendFile.Close();
                client.Close();
            }
        }
        #endregion

        #region files' length
        public static void Status(Socket client, string com, byte[] buf)
        {
            client.Send(Encoding.UTF8.GetBytes(com));
            int tRead = client.Receive(buf);
            string message = Encoding.UTF8.GetString(buf, 0, tRead);
            Console.WriteLine(message);
        }
        #endregion

        #region invalid commands
        public static void Invalid(Socket client, string com, byte[] buf)
        {
            client.Send(Encoding.UTF8.GetBytes(com));
            int tRead = client.Receive(buf);
            string message = Encoding.UTF8.GetString(buf, 0, tRead);
            Console.WriteLine(message);
        }
        #endregion

        static void Main(string[] args)
        {
            string com = ShowOrder();

            if (com == "quit" || com.Length < 4)
            {
                Console.WriteLine("Goodbye");
            }
            else
            {
                string order = com.Substring(0, 4);
                order = order.ToLower();
                string filename = com.Substring(5);
                filename = filename.Trim();
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect("localhost", 23456);
                if (client.Connected)
                    Console.WriteLine("connect successfully!");
                byte[] buf = new byte[BufSize];
                switch (order)
                {
                    case "retr": Retrieve(client, com, buf, filename);
                        break;
                    case "stor": Store(client, com, buf, filename);
                        break;
                    case "stat": Status(client, com, buf);
                        break;
                    default: Invalid(client, com, buf);
                        break;
                }
                Console.ReadKey();
                client.Close();
            }
        }
    }
}

符合的要求:

现定义两种命令:stat <pathname><CRLF>                 ①

与                                 retr<pathname><CRLF>                ②

 

1, <pathname>为路径名,或为绝对路径(若为绝对路径则以字符’/’开头),或为相对路径。

2, <CRLF>为”\r\n”两个字符组成的字符串,为命令的分隔符。

3, 除参数外,命令名不区分大小写,即stat、Stat、STAT、StAt都一样。

4, 命令以UTF-8格式传输,例子请看AppendixI。

 

命令功能:

①  请求获取文件属性(目前只有长度),以字符串的形式返回。

②  请求建立连接,并开始从服务器中下载<pathname>文件。


服务器:

1,  现要求文件服务器里有若干个文件,每个文件(假设)只有一种属性:长度(in bytes)。

当收到stat查询请求时,获取参数<pathname>指定的文件长度,并以字符串形式返回给客户端。

2,  当收到retr下传请求时,则开始向客户端写入<pathname>指定的文件数据。


当上传下载文件时,没有对文件进行检查。

当热,这样的程序也只是玩玩,练练手。(厉害的我还不会)

如果有什么不足,错误的,希望大家能够指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值