Socket 传输文件

/*
 * 由SharpDevelop创建。
 * 用户: Changweihua
 * 日期: 2013/7/2
 * 时间: 8:55
 *
 * changweihua@outlook.com
 * http://www.cmono.net
 *
 */
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
namespace FileClient
{
    class Program
    {
        static void SendFile(string path, string ip, int port)
        {
            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse(ip), port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(remoteIP);
            }
            catch (Exception)
            {
                Console.WriteLine("无法连接到远程主机");
            }
            if(socket.Connected)
            {
                FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
                string fileName = fs.Name;
                int begin = fileName.LastIndexOf("\\");
                fileName = fileName.Substring(begin + 1, fileName.Length - begin - 1);
                fileName += "#";
                                
                byte[] fileNameBuffer = new byte[1024];
                fileNameBuffer = Encoding.UTF8.GetBytes(fileName);
                socket.Send(fileNameBuffer, 0, fileNameBuffer.Length, SocketFlags.None);
                                
                byte[] fileBuffer = new byte[1024];
                int bytesRead;
                int totalBytes = 0;
                                
                try
                {
                    do
                    {
                        bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length);
                        socket.Send(fileBuffer, 0, bytesRead, SocketFlags.None);
                        totalBytes += bytesRead;
                        Console.WriteLine("已发送成功 {0} 字节", bytesRead);
                    }while(bytesRead > 0);
                    Console.WriteLine("发送成功 {0} 字节", totalBytes);
                    fs.Close();
                    socket.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                                
            }
        }
                        
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
                            
            SendFile("E:\\PluginInstaller.msi", "127.0.0.1", 10000);
                            
            Console.ReadKey(true);
        }
    }
}

/*
 * 由SharpDevelop创建。
 * 用户: Changweihua
 * 日期: 2013/7/2
 * 时间: 8:54
 *
 * changweihua@outlook.com
 * http://www.cmono.net
 *
 */
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;
namespace FileServer
{
    class Program
    {
                
                
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
                    
            Recevier receiver = new Recevier();
            receiver.Start();
                    
            Console.ReadKey(true);
        }
    }
            
            
    class Recevier
    {
        Thread recvThread;
        Socket listenSocket;
                
        public void Start()
        {
            recvThread = new Thread(new ThreadStart(Recv));
            recvThread.IsBackground = false;
            recvThread.Start();
        }
                
        private void Recv()
        {
            IPEndPoint local = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10000);
            EndPoint localEP = (EndPoint)local;
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(localEP);
            listenSocket.Listen(10);
                    
            while (true)
            {
                Socket socket = listenSocket.Accept();
                if(socket.Connected)
                {
                    //接收文件名
                    byte[] fileNameBuffer = new byte[1024];
                    socket.Receive(fileNameBuffer, 0, fileNameBuffer.Length, SocketFlags.None);
                    string fileName = Encoding.UTF8.GetString(fileNameBuffer);
                    string[] str = fileName.Split(new char[]{ '#' });
                    fileName = str[0];
                    string pathRecv = "D:\\" + fileName;
                    Console.WriteLine("文件名:{0}", fileName);
                            
                    //接收文件内容
                    FileStream fs = new FileStream(pathRecv, FileMode.OpenOrCreate);
                    byte[] buffer = new byte[1024];
                    int bytesRecv;
                    int totalBytes = 0;
                    do
                    {
                        bytesRecv = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                        totalBytes += bytesRecv;  
                        fs.Write(buffer, 0, bytesRecv);
                        Console.WriteLine("已接收成功 {0} 字节", bytesRecv);
                    }while(bytesRecv > 0);
                    Console.WriteLine("接收成功,共计 {0} 字节", totalBytes);
                    socket.Close();
                    fs.Close();
                }
            }
                    
        }
    }
}

点击查看原图

知识共享许可协议
《Socket 传输文件》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     164.61ms