基本信息
源码名称:C# Socket文件传输源码
源码大小:0.08M
文件格式:.rar
开发语言:C#
更新时间:2018-06-25
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

Socket文件传输源码,实现了 服务端向客户端 发送文件 功能


功能介绍:
    使用socket实现文件传输同时使用了多线程,
首先服务端选择文件,开始监听启动客户端,选
择连接就实现了文件的传输。

注意:
    不同机器连接要修改源代码的的ip地址。
    开发环境为Visual Studio 2010




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;

namespace FileServer
{
    public partial class Form2 : Form
    { 
        Socket Listensocket;
        Thread listenThread;
        //_5_1_a_s_p_x
        public Form2()
        {
            InitializeComponent();
        }

        //选择文件
        private void BtnSelectFile_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileInfo fileinfo = new FileInfo(this.openFileDialog1.FileName);
                tbFileName.Text = fileinfo.FullName;
                tbFileSize.Text = fileinfo.Length.ToString();
            }
        }
        
        //开始监听
        private void btnListen_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbFileName.Text) && !string.IsNullOrEmpty(tbFileSize.Text))
            {
                //服务端节点    
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

                //创建套接字         
                Listensocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //绑定IP地址和端口到套接字    
                Listensocket.Bind(ipep);

                //启动监听          
                Listensocket.Listen(10);
                listBox1.Items.Add("开始监听客户端的连接请求");

                //在一个单独的线程中监听客户连接       
                listenThread = new Thread(listenClientConnnect);
                listenThread.Start();
                btnListen.Enabled = false;
            }
            else
            {
                MessageBox.Show("请浏览文件", "提醒信息");
            }
        }
           
        //监听函数
        private void listenClientConnnect()
        {
            stopListen();//停用
            while (true)
            {
                //建立一个与客户端通信的套接字 
                Socket CommunicationSocket = Listensocket.Accept();

                //显示在listbox里面
                IPEndPoint clientIP = (IPEndPoint)CommunicationSocket.RemoteEndPoint;
               
                AddMsg(string.Format("{0} 连接到本服务器 {1}", clientIP.Address, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                //创建一个文件对象     
                FileInfo fileinfo = new FileInfo(tbFileName.Text);

                //打开文件流            
                FileStream filestream = fileinfo.OpenRead();

                //文件分块传输,分块的大小,单位为字节         
                int PacketSize = 5000;
                //分块的数量               
                int PacketCount = (int)(fileinfo.Length / ((long)PacketSize));
                //最后一个分块的大小           
                int LastPacketSize = (int)(fileinfo.Length - ((long)(PacketSize * PacketCount)));

                //发送文件名到接收端,文件名长度最多只允许100个字节       
                byte[] Fullfilename = new byte[100];
                if (System.Text.Encoding.UTF8.GetBytes(fileinfo.Name).Length > 100)
                {
                    MessageBox.Show("文件名太长");
                    break;
                }
                else
                {
                    byte[] filename = System.Text.Encoding.UTF8.GetBytes(fileinfo.Name);
                    for (int i = 0; i < filename.Length; i  )
                        Fullfilename[i] = filename[i];
                    CommunicationSocket.Send(Fullfilename);
                }


                //文件按数据包的形式发送,定义数据包的大小      
                byte[] data = new byte[PacketSize];
                //开始循环发送数据包           
                for (int i = 0; i < PacketCount; i  )
                {
                    //从文件流读取数据并填充数据包  
                    filestream.Read(data, 0, data.Length);
                    //发送数据包                    
                    CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
                }
                //发送最后一个数据包   
                if (LastPacketSize != 0)
                {
                    data = new byte[LastPacketSize];
                    filestream.Read(data, 0, data.Length);
                    //发送数据包             
                    CommunicationSocket.Send(data, 0, data.Length, SocketFlags.None);
                }
                filestream.Close();
                CommunicationSocket.Close();               
                AddMsg(string.Format("向{0} 发送 文件 已完成 {1}", clientIP, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
        }

        //关闭
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Listensocket!=null)
            { 
                Listensocket.Close();    
            }
        }

        //停止监听
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (listenThread.IsAlive)
            {
                listenThread.Abort();
                btnListen.Enabled = true;
                btnStop.Enabled = false;
                if (Listensocket!=null)
                {
                    Listensocket.Close();
                }
                listBox1.Items.Add("服务器监听已经停止...");

            }
        }

        //加载
        private void Form2_Load(object sender, EventArgs e)
        {
            btnStop.Enabled = false;
            btnListen.Enabled = true;
        }

        //停止监听
        private void stopListen()
        {
            if (btnStop.InvokeRequired)
            {
                Action stopAction = () => { stopListen(); };
                btnStop.Invoke(stopAction);
            }
            else
            {
                btnStop.Enabled = true;
            }
        }

        //向listBox中增加信息
        private void AddMsg(string msgStr)
        {
            if (listBox1.InvokeRequired)
            {
                Action<string> myAction = (p) => { AddMsg(p); };
                this.listBox1.Invoke(myAction, msgStr);
            }
            else
            {
                this.listBox1.Items.Add(msgStr);
            }
        }
    }
}