客户机给服务器发送文件,通过SOCKE通信

客户端部门,一个选择文件的按钮

一个提示lable

一个时钟控件:

代码部门如下,

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


//That code is written by Suman Biswas, Calcutta, India (Email: sumanbiswas@aol.in,Website: sumanbiswas.xm.com).
//That code is running to transfer small file to client to server. by using and after doing modification any one
//can able to make a large file transfer application in C#.Net. This is Client code.
namespace FTClientCode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FileDialog fDg = new OpenFileDialog();
            if (fDg.ShowDialog() == DialogResult.OK)
            {
                FTClientCode.SendFile(fDg.FileName);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label3.Text = FTClientCode.curMsg;
        }
    }

    //FILE TRANSFER USING C#.NET SOCKET - CLIENT
    class FTClientCode
    {
        public static string curMsg = "Idle";
        public static void SendFile(string fileName)
        {
            try
            {
                IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
                IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
                Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);


                string filePath = "";

                fileName = fileName.Replace("\", "/");
                while (fileName.IndexOf("/") > -1)
                {
                    filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                    fileName = fileName.Substring(fileName.IndexOf("/") + 1);
                }


                //byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
                byte[] fileNameByte = Encoding.GetEncoding("GB2312").GetBytes(fileName);
                if (fileNameByte.Length > 850 * 1024)
                {
                    curMsg = "File size is more than 850kb, please try with small file.";
                    return;
                }

                curMsg = "Buffering ...";
                byte[] fileData = File.ReadAllBytes(filePath + fileName);
                byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
                byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

                fileNameLen.CopyTo(clientData, 0);
                fileNameByte.CopyTo(clientData, 4);
                fileData.CopyTo(clientData, 4 + fileNameByte.Length);

                curMsg = "Connection to server ...";
                clientSock.Connect(ipEnd);//建立与远程主机的连接

                curMsg = "File sending...";
                clientSock.Send(clientData);

                curMsg = "Disconnecting...";
                clientSock.Close();
                curMsg = "File transferred.";
               
            }
            catch (Exception ex)
            {
                if(ex.Message=="No connection could be made because the target machine actively refused it")
                    curMsg="File Sending fail. Because server not running." ;
                else
                    curMsg = "File Sending fail." + ex.Message;
            }

        }
    }
}

服务器端:

一个选择存放接收到文件的路径按钮,

一个开始接收文件的按钮

一个时钟

一个backgroundWorker1控件

解决了传输文件不能是汉语的问题。

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

//That code is written by Suman Biswas, Calcutta, India (Email: sumanbiswas@aol.in,Website: sumanbiswas.xm.com).
//That code is running to transfer small file to client to server. by using and after doing modification any one
//can able to make a large file transfer application in C#.Net. This is Server code.

namespace FTServerCode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            FTServerCode.receivedPath = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (FTServerCode.receivedPath.Length > 0)
                backgroundWorker1.RunWorkerAsync();//开始执行后台操作
            else
                MessageBox.Show("Please select file receiving path");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = FTServerCode.receivedPath;
            label3.Text = FTServerCode.curMsg;
        }

        FTServerCode obj = new FTServerCode();
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
           
            obj.StartServer();           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                FTServerCode.receivedPath = fd.SelectedPath;
            }
        }
    }
    //FILE TRANSFER USING C#.NET SOCKET - SERVER
    class FTServerCode
    {
        IPEndPoint ipEnd;
        Socket sock;
        public FTServerCode()
        {
           ipEnd = new IPEndPoint(IPAddress.Any, 5656);//提供一个IP 地址,指示服务器应监听网络接口上的客户端活动
           sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
           sock.Bind(ipEnd);//sock与本地的一个终结点相关联
        }
        public static string receivedPath;
        public static string curMsg = "Stopped";
        public  void StartServer()
        {
            try
            {
                curMsg = "Starting...";
                sock.Listen(100);

                curMsg = "Running and waiting to receive file.";
                Socket clientSock = sock.Accept();

                byte[] clientData = new byte[1024 * 5000];
               
                int receivedBytesLen = clientSock.Receive(clientData);
                curMsg = "Receiving data...";

                int fileNameLen = BitConverter.ToInt32(clientData, 0);//返回字节数组中指定位置的四个字节转化成32位有符号整数
                //string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);//
                string fileName = Encoding.GetEncoding("GB2312").GetString(clientData, 4, fileNameLen);
                BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;
                bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);

                curMsg = "Saving file...";

                bWrite.Close();
                clientSock.Close();
                curMsg = "Reeived & Saved file; Server Stopped.";
            }
            catch (Exception ex)
            {
                curMsg = "File Receving error.";
            }
        }
    }
}

原文地址:https://www.cnblogs.com/liujicai/p/3584469.html