• c#中Socket进行文件传输


    Server段代码

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    
    namespace SocketSendFileServer
    {
        class Program
        {
            const int BufferSize = 1024;
            static string path = @"E:";
            static void Main(string[] args)
            {
                IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Bind(ip);
                sock.Listen(1);
                Console.WriteLine("Begin listen...");
    
                while (true)
                {
                    Socket client = sock.Accept();
                    if (client.Connected)
                    {
                        Thread cThread = new Thread(new ParameterizedThreadStart(myClient));
                        cThread.IsBackground = true;
                        cThread.Start(client);
                    }
                }
            }
    
    
            static void myClient(object oSocket)
            {
                Socket clientSocket = (Socket)oSocket;
                string clientName = clientSocket.RemoteEndPoint.ToString();
                Console.WriteLine("新来一个客户:" + clientName);
                try
                {
                    while (true)
                    {
                        byte[] buffer = new byte[BufferSize];
                        int count = clientSocket.Receive(buffer);
                        Console.WriteLine("收到" + clientName + ":" + Encoding.Default.GetString(buffer, 0, count));
                        string[] command = Encoding.Default.GetString(buffer, 0, count).Split(',');
                        string fileName;
                        long length;
                        if (command[0] == "namelength")
                        {
                            fileName = command[1];
                            length = Convert.ToInt64(command[2]);
                            clientSocket.Send(Encoding.Default.GetBytes("OK"));
                            long receive = 0L;
                            Console.WriteLine("Receiveing file:" + fileName + ".Plz wait...");
                            using (FileStream writer = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                int received;
                                while (receive < length)
                                {
                                    received = clientSocket.Receive(buffer);
                                    writer.Write(buffer, 0, received);
                                    writer.Flush();
                                    receive += (long)received;
                                }
                            }
                            Console.WriteLine("Receive finish.
    ");
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("客户:" + clientName + "退出");
                }
    
            }
        }
    }

    Client段代码

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace SocketFileClient
    {
        class Program
        {
            static Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            static void Main(string[] args)
            {
                sock.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
                Console.WriteLine("Connect successfully");
                while (true)
                {
                    Console.WriteLine("please input the path of the file which you want to send:");
                    string path = Console.ReadLine();
                    try
                    {
                        using (FileStream reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            long send = 0L, length = reader.Length;
                            string sendStr = "namelength," + Path.GetFileName(path) + "," + length.ToString();
    
                            string fileName = Path.GetFileName(path);
                            sock.Send(Encoding.Default.GetBytes(sendStr));
    
                            int BufferSize = 1024;
                            byte[] buffer = new byte[32];
                            sock.Receive(buffer);
                            string mes = Encoding.Default.GetString(buffer);
    
                            if (mes.Contains("OK"))
                            {
                                Console.WriteLine("Sending file:" + fileName + ".Plz wait...");
                                byte[] fileBuffer = new byte[BufferSize];
                                int read, sent;
                                while ((read = reader.Read(fileBuffer, 0, BufferSize)) != 0)
                                {
                                    sent = 0;
                                    while ((sent += sock.Send(fileBuffer, sent, read, SocketFlags.None)) < read)
                                    {
                                        send += (long)sent;
                                    }
                                }
                                Console.WriteLine("Send finish.
    ");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
    }
  • 相关阅读:
    15道简单算法题
    提高SQL查询效率
    算法--两道百度笔试题
    .NET牛人应该知道些什么?
    VS创建、安装、调试 windows服务(windows service)
    Build System 和Test Framework overview总结
    3.8 Templates -- Actions
    3.7 Templates -- Links
    3.6 Templates -- Binding Element Class Names(绑定元素类名)
    3.5 Templates -- Binding Element Attributes(绑定元素属性)
  • 原文地址:https://www.cnblogs.com/mlgm/p/11708976.html
Copyright © 2020-2023  润新知