C# socket 發送圖片和文件


先說服務端:界面:如圖:

界面設計源碼

namespace SocketJPGToTxt
{
    partial class Form1
    {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的代碼

        /// <summary>
        /// 設計器支持所需的方法 - 不要修改
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.txtMsg = new System.Windows.Forms.TextBox();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.cboUsers = new System.Windows.Forms.ComboBox();
            this.listBox2 = new System.Windows.Forms.ListBox();
            this.txtPath = new System.Windows.Forms.TextBox();
            this.btnSelect = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.btnSend = new System.Windows.Forms.Button();
            this.btnZD = new System.Windows.Forms.Button();
            this.txtLog = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // txtMsg
            // 
            this.txtMsg.Location = new System.Drawing.Point(22, 28);
            this.txtMsg.Name = "txtMsg";
            this.txtMsg.Size = new System.Drawing.Size(166, 21);
            this.txtMsg.TabIndex = 0;
            this.txtMsg.Text = "127.0.0.1";
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(194, 28);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(100, 21);
            this.txtPort.TabIndex = 1;
            this.txtPort.Text = "8081";
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(351, 25);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 2;
            this.btnStart.Text = "開啟監聽";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // cboUsers
            // 
            this.cboUsers.FormattingEnabled = true;
            this.cboUsers.Location = new System.Drawing.Point(491, 25);
            this.cboUsers.Name = "cboUsers";
            this.cboUsers.Size = new System.Drawing.Size(121, 20);
            this.cboUsers.TabIndex = 3;
            // 
            // listBox2
            // 
            this.listBox2.FormattingEnabled = true;
            this.listBox2.ItemHeight = 12;
            this.listBox2.Location = new System.Drawing.Point(13, 193);
            this.listBox2.Name = "listBox2";
            this.listBox2.Size = new System.Drawing.Size(668, 124);
            this.listBox2.TabIndex = 5;
            // 
            // txtPath
            // 
            this.txtPath.Location = new System.Drawing.Point(33, 338);
            this.txtPath.Name = "txtPath";
            this.txtPath.Size = new System.Drawing.Size(298, 21);
            this.txtPath.TabIndex = 6;
            // 
            // btnSelect
            // 
            this.btnSelect.Location = new System.Drawing.Point(351, 336);
            this.btnSelect.Name = "btnSelect";
            this.btnSelect.Size = new System.Drawing.Size(75, 23);
            this.btnSelect.TabIndex = 7;
            this.btnSelect.Text = "瀏覽";
            this.btnSelect.UseVisualStyleBackColor = true;
            this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(467, 335);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 8;
            this.button3.Text = "發送文件";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.btnSendFile_Click);
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(158, 387);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(75, 23);
            this.btnSend.TabIndex = 9;
            this.btnSend.Text = "發送消息";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // btnZD
            // 
            this.btnZD.Location = new System.Drawing.Point(363, 386);
            this.btnZD.Name = "btnZD";
            this.btnZD.Size = new System.Drawing.Size(75, 23);
            this.btnZD.TabIndex = 10;
            this.btnZD.Text = "震動";
            this.btnZD.UseVisualStyleBackColor = true;
            this.btnZD.Click += new System.EventHandler(this.btnZD_Click);
            // 
            // txtLog
            // 
            this.txtLog.Location = new System.Drawing.Point(22, 65);
            this.txtLog.Multiline = true;
            this.txtLog.Name = "txtLog";
            this.txtLog.Size = new System.Drawing.Size(659, 96);
            this.txtLog.TabIndex = 11;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.txtLog);
            this.Controls.Add(this.btnZD);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.btnSelect);
            this.Controls.Add(this.txtPath);
            this.Controls.Add(this.listBox2);
            this.Controls.Add(this.cboUsers);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.txtPort);
            this.Controls.Add(this.txtMsg);
            this.Name = "Form1";
            this.Text = "Socket服務端";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txtMsg;
        private System.Windows.Forms.TextBox txtPort;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.ComboBox cboUsers;
        private System.Windows.Forms.ListBox listBox2;
        private System.Windows.Forms.TextBox txtPath;
        private System.Windows.Forms.Button btnSelect;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.Button btnZD;
        private System.Windows.Forms.TextBox txtLog;
    }
}
View Code

界面邏輯源碼

namespace SocketJPGToTxt
{
    public partial class Form1 : Form
    {
        //說明:在傳遞信息的時候,會在需要傳遞的信息前面加一個字符來標識傳遞的是不同的信息
        // 0:表示傳遞的是字符串信息
        // 1:表示傳遞的是文件信息
        // 2:表示的是震動

        /// <summary>
        /// 用來存放連接服務的客戶端的IP地址和端口號,對應的Socket
        /// </summary>
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //不檢測跨線程之間的空間調用
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 開啟監聽
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //當點擊開始監聽的時候 在服務器端創建一個負責監IP地址跟端口號的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //獲取IP
                IPAddress ip = IPAddress.Any;
                //創建端口號
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //監聽
                socketWatch.Bind(port);
                ShowMsg("監聽成功");
                socketWatch.Listen(10);
                //新建線程,去接收客戶端發來的信息
                Thread td = new Thread(AcceptMgs);
                td.IsBackground = true;
                td.Start(socketWatch);
            }
            catch
            {

            }
        }

        /// <summary>
        /// 接收客戶端發送的信息
        /// </summary>
        /// <param name="o"></param>
        private void AcceptMgs(object o)
        {
            try
            {
                Socket socketWatc = (Socket)o;
                while (true)
                {
                    ////負責跟客戶端通信的Socket
                    Socket socketSend = socketWatc.Accept();
                    //將遠程連接的客戶端的IP地址和Socket存入集合中
                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    //將遠程連接的客戶端的IP地址和端口號存儲下拉框中
                    cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ": 連接成功");
                    //新建線程循環接收客戶端發來的信息
                    Thread td = new Thread(Recive);
                    td.IsBackground = true;
                    td.Start(socketSend);
                }
            }
            catch { }

        }

        /// <summary>
        /// 接收客戶端發來的數據,並顯示出來
        /// </summary>
        private void Recive(object o)
        {
            Socket socketSend = (Socket)o;
            try
            {
                while (true)
                {
                    //客戶端連接成功后,服務器應該接受客戶端發來的消息

                    if (socketSend == null)
                    {
                        MessageBox.Show("請選擇要發送的客戶端");
                        continue;
                    }
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //實際接受到的有效字節數
                    int r = socketSend.Receive(buffer);
                    //如果客戶端關閉,發送的數據就為空,然后就跳出循環
                    if (r == 0)
                    {
                        break;
                    }
                    if (buffer[0] == 0) //如果接收的字節數組的第一個字節是0,說明接收的字符串信息
                    {
                        string strMsg = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
                    }
                    else if (buffer[0] == 1) //如果接收的字節數組的第一個字節是1,說明接收的是文件
                    {
                        string filePath = "";
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Title = "保存文件";
                        sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
                        sfd.Filter = "文本文件|*.txt|圖片文件|*.jpg|視頻文件|*.avi|所有文件|*.*";
                        //如果沒有選擇保存文件路徑就一直打開保存框
                        while (true)
                        {
                            sfd.ShowDialog(this);
                            filePath = sfd.FileName;
                            if (string.IsNullOrEmpty(filePath))
                            {
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                        //保存接收的文件
                        using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功");

                    }
                    else if (buffer[0] == 2) //如果接收的字節數組的第一個字節是2,說明接收的是震動
                    {
                        ZD();
                    }
                }
            }
            catch { }
        }


        /// <summary>
        /// 顯示信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMsg(string message)
        {
            txtLog.AppendText(message + "\r\n");
        }

        /// <summary>
        /// 發送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {

            //獲得選中客戶端ip對應的通信Socket      
            if (cboUsers.SelectedItem == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
            if (socketSend == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            string strSend = txtMsg.Text;
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(strSend);
                //獲得發送的信息時候,在數組前面加上一個字節 0
                List<byte> list = new List<byte>();
                list.Add(0);
                list.AddRange(buffer);
                //將泛型集合轉換為數組
                byte[] newBuffer = list.ToArray();
                //將了標識字符的字節數組傳遞給客戶端
                socketSend.Send(newBuffer);
                txtMsg.Text = "";
            }
            catch
            {
            }
        }

        /// <summary>
        /// 選擇文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            //打開文件
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "選擇要傳的文件";
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            ofd.Filter = "文本文件|*.txt|圖片文件|*.jpg|視頻文件|*.avi|所有文件|*.*";
            ofd.ShowDialog();
            //得到選擇文件的路徑
            txtPath.Text = ofd.FileName;
        }

        /// <summary>
        /// 發送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            //判斷是否選擇了要發送的客戶端
            if (cboUsers.SelectedItem == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
            if (socketSend == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            string filePath = txtPath.Text;
            if (string.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("請選擇文件");
                return;
            }
            Thread td = new Thread(SendBigFile);
            td.IsBackground = true;
            td.Start();

        }

        /// <summary>
        /// 大文件斷點傳送
        /// </summary>
        private void SendBigFile()
        {
            string filePath = txtPath.Text;
            Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
            try
            {
                //讀取選擇的文件
                using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    //1. 第一步:發送一個包,表示文件的長度,讓客戶端知道后續要接收幾個包來重新組織成一個文件
                    long length = fsRead.Length;
                    byte[] byteLength = Encoding.UTF8.GetBytes(length.ToString());
                    //獲得發送的信息時候,在數組前面加上一個字節 1
                    List<byte> list = new List<byte>();
                    list.Add(1);
                    list.AddRange(byteLength);
                    socketSend.Send(list.ToArray()); //
                                                     //2. 第二步:每次發送一個1MB的包,如果文件較大,則會拆分為多個包
                    byte[] buffer = new byte[1024 * 1024];
                    long send = 0; //發送的字節數                  
                    while (true)  //大文件斷點多次傳輸
                    {
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        if (r == 0)
                        {
                            break;
                        }
                        socketSend.Send(buffer, 0, r, SocketFlags.None);
                        send += r;
                        ShowMsg(string.Format("{0}: 已發送:{1}/{2}", socketSend.RemoteEndPoint, send, length));
                    }
                    ShowMsg("發送完成");
                    txtPath.Text = "";
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 震動
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZD_Click(object sender, EventArgs e)
        {
            //判斷是否選擇了要發送的客戶端
            if (cboUsers.SelectedItem == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            Socket socketSend = dicSocket[cboUsers.SelectedItem.ToString()];
            if (socketSend == null)
            {
                MessageBox.Show("請選擇要發送的客戶端");
                return;
            }
            try
            {
                // 首字節是2說明是震動
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                socketSend.Send(buffer);
            }
            catch
            {

            }

        }

        /// <summary>
        /// 震動
        /// </summary>
        private void ZD()
        {
            //獲取當前窗體的坐標
            Point point = this.Location;
            //反復給窗體坐標復制一百次,達到震動的效果
            for (int i = 0; i < 100; i++)
            {
                this.Location = new Point(point.X - 5, point.Y - 5);
                this.Location = new Point(point.X + 5, point.Y + 5);
            }
            this.Location = point;
        }
    }
}
View Code

然后客戶端界面:

客戶端界面源碼:

 

namespace SocketJPGToTxtClient
{
    partial class Form1
    {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的代碼

        /// <summary>
        /// 設計器支持所需的方法 - 不要修改
        /// 使用代碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.txtLog = new System.Windows.Forms.TextBox();
            this.btnZD = new System.Windows.Forms.Button();
            this.btnSend = new System.Windows.Forms.Button();
            this.btnSendFile = new System.Windows.Forms.Button();
            this.btnSelect = new System.Windows.Forms.Button();
            this.txtPath = new System.Windows.Forms.TextBox();
            this.listBox2 = new System.Windows.Forms.ListBox();
            this.cboUsers = new System.Windows.Forms.ComboBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.txtServer = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // txtLog
            // 
            this.txtLog.Location = new System.Drawing.Point(75, 73);
            this.txtLog.Multiline = true;
            this.txtLog.Name = "txtLog";
            this.txtLog.Size = new System.Drawing.Size(659, 96);
            this.txtLog.TabIndex = 22;
            // 
            // btnZD
            // 
            this.btnZD.Location = new System.Drawing.Point(416, 394);
            this.btnZD.Name = "btnZD";
            this.btnZD.Size = new System.Drawing.Size(75, 23);
            this.btnZD.TabIndex = 21;
            this.btnZD.Text = "震動";
            this.btnZD.UseVisualStyleBackColor = true;
            this.btnZD.Click += new System.EventHandler(this.btnZD_Click);
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(211, 395);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(75, 23);
            this.btnSend.TabIndex = 20;
            this.btnSend.Text = "發送消息";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // btnSendFile
            // 
            this.btnSendFile.Location = new System.Drawing.Point(520, 343);
            this.btnSendFile.Name = "btnSendFile";
            this.btnSendFile.Size = new System.Drawing.Size(75, 23);
            this.btnSendFile.TabIndex = 19;
            this.btnSendFile.Text = "發送文件";
            this.btnSendFile.UseVisualStyleBackColor = true;
            this.btnSendFile.Click += new System.EventHandler(this.btnSendFile_Click);
            // 
            // btnSelect
            // 
            this.btnSelect.Location = new System.Drawing.Point(404, 344);
            this.btnSelect.Name = "btnSelect";
            this.btnSelect.Size = new System.Drawing.Size(75, 23);
            this.btnSelect.TabIndex = 18;
            this.btnSelect.Text = "瀏覽";
            this.btnSelect.UseVisualStyleBackColor = true;
            this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click);
            // 
            // txtPath
            // 
            this.txtPath.Location = new System.Drawing.Point(86, 346);
            this.txtPath.Name = "txtPath";
            this.txtPath.Size = new System.Drawing.Size(298, 21);
            this.txtPath.TabIndex = 17;
            // 
            // listBox2
            // 
            this.listBox2.FormattingEnabled = true;
            this.listBox2.ItemHeight = 12;
            this.listBox2.Location = new System.Drawing.Point(66, 201);
            this.listBox2.Name = "listBox2";
            this.listBox2.Size = new System.Drawing.Size(668, 124);
            this.listBox2.TabIndex = 16;
            // 
            // cboUsers
            // 
            this.cboUsers.FormattingEnabled = true;
            this.cboUsers.Location = new System.Drawing.Point(544, 33);
            this.cboUsers.Name = "cboUsers";
            this.cboUsers.Size = new System.Drawing.Size(121, 20);
            this.cboUsers.TabIndex = 15;
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(404, 33);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 14;
            this.btnStart.Text = "連接";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(247, 36);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(100, 21);
            this.txtPort.TabIndex = 13;
            this.txtPort.Text = "8081";
            // 
            // txtServer
            // 
            this.txtServer.Location = new System.Drawing.Point(75, 36);
            this.txtServer.Name = "txtServer";
            this.txtServer.Size = new System.Drawing.Size(166, 21);
            this.txtServer.TabIndex = 12;
            this.txtServer.Text = "127.0.0.1";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.txtLog);
            this.Controls.Add(this.btnZD);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this.btnSendFile);
            this.Controls.Add(this.btnSelect);
            this.Controls.Add(this.txtPath);
            this.Controls.Add(this.listBox2);
            this.Controls.Add(this.cboUsers);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.txtPort);
            this.Controls.Add(this.txtServer);
            this.Name = "Form1";
            this.Text = "Client";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txtLog;
        private System.Windows.Forms.Button btnZD;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.Button btnSendFile;
        private System.Windows.Forms.Button btnSelect;
        private System.Windows.Forms.TextBox txtPath;
        private System.Windows.Forms.ListBox listBox2;
        private System.Windows.Forms.ComboBox cboUsers;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.TextBox txtPort;
        private System.Windows.Forms.TextBox txtServer;
    }
}
View Code

客戶端界面邏輯代碼

namespace SocketJPGToTxtClient
{
    public partial class Form1 : Form
    {
        //說明:在傳遞信息的時候,會在需要傳遞的信息前面加一個字符來標識傳遞的是不同的信息
        // 0:表示傳遞的是字符串信息
        // 1:表示傳遞的是文件信息
        // 2:表示的是震動

        /// <summary>
        /// 用來存放連接服務的IP地址和端口號,對應的Socket (這個為了以后的擴展用,現在暫時沒用)
        /// </summary>
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        /// <summary>
        /// 存儲保存文件的路徑
        /// </summary>
        string filePath = "";
        /// <summary>
        /// 負責通信的Socket
        /// </summary>
        Socket socketSend;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //不檢測跨線程之間的空間調用
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 建立連接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //創建負責通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //獲取服務端的IP
                IPAddress ip = IPAddress.Parse(txtServer.Text.Trim());
                //獲取服務端的端口號
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //獲得要連接的遠程服務器應用程序的IP地址和端口號
                socketSend.Connect(port);
                ShowMsg("連接成功");
                //新建線程,去接收客戶端發來的信息
                Thread td = new Thread(AcceptMgs);
                td.IsBackground = true;
                td.Start();
            }
            catch { }
        }

        /// <summary>
        /// 接收數據
        /// </summary>
        private void AcceptMgs()
        {
            try
            {
                /// <summary>
                /// 存儲大文件的大小
                /// </summary>
                long length = 0;
                long recive = 0; //接收的大文件總的字節數
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    if (length > 0)  //判斷大文件是否已經保存完
                    {
                        //保存接收的文件
                        using (FileStream fsWrite = new FileStream(filePath, FileMode.Append, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 0, r);
                            length -= r; //減去每次保存的字節數
                            ShowMsg(string.Format("{0}: 已接收:{1}/{2}", socketSend.RemoteEndPoint, recive - length, recive));
                            if (length <= 0)
                            {
                                ShowMsg(socketSend.RemoteEndPoint + ": 接收文件成功");
                            }
                            continue;
                        }
                    }
                    if (buffer[0] == 0) //如果接收的字節數組的第一個字節是0,說明接收的字符串信息
                    {
                        string strMsg = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
                    }
                    else if (buffer[0] == 1) //如果接收的字節數組的第一個字節是1,說明接收的是文件
                    {
                        length = int.Parse(Encoding.UTF8.GetString(buffer, 1, r - 1));
                        recive = length;
                        filePath = "";
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Title = "保存文件";
                        sfd.InitialDirectory = @"C:\Users\Administrator\Desktop";
                        sfd.Filter = "文本文件|*.txt|圖片文件|*.jpg|視頻文件|*.avi|所有文件|*.*";
                        //如果沒有選擇保存文件路徑就一直打開保存框
                        while (true)
                        {
                            sfd.ShowDialog(this);
                            filePath = sfd.FileName;
                            if (string.IsNullOrEmpty(filePath))
                            {
                                continue;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else if (buffer[0] == 2) //如果接收的字節數組的第一個字節是2,說明接收的是震動
                    {
                        ZD();
                    }
                }
            }
            catch { }


        }


        /// <summary>
        /// 顯示信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMsg(string message)
        {
            txtLog.AppendText(message + "\r\n");
        }

        /// <summary>
        /// 發送數據
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(txtServer.Text);
                //獲得發送的信息時候,在數組前面加上一個字節 0
                List<byte> list = new List<byte>();
                list.Add(0);
                list.AddRange(buffer);
                //將泛型集合轉換為數組
                byte[] newBuffer = list.ToArray();
                //將了標識字符的字節數組傳遞給客戶端
                socketSend.Send(newBuffer);
                txtServer.Text = "";
            }
            catch { }
        }

        /// <summary>
        /// 選擇文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            //打開文件
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "選擇要傳的文件";
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            ofd.Filter = "文本文件|*.txt|圖片文件|*.jpg|視頻文件|*.avi|所有文件|*.*";
            ofd.ShowDialog();
            //得到選擇文件的路徑
            txtPath.Text = ofd.FileName;
        }

        /// <summary>
        /// 發送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = txtPath.Text;
                if (string.IsNullOrEmpty(filePath))
                {
                    MessageBox.Show("請選擇文件");
                    return;
                }
                //讀取選擇的文件
                using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = fsRead.Read(buffer, 0, buffer.Length);
                    //獲得發送的信息時候,在數組前面加上一個字節 1
                    List<byte> list = new List<byte>();
                    list.Add(1);
                    list.AddRange(buffer);
                    byte[] newBuffer = list.ToArray();
                    //將了標識字符的字節數組傳遞給客戶端
                    socketSend.Send(newBuffer, 0, r + 1, SocketFlags.None);
                    txtPath.Text = "";
                }
            }
            catch { }
        }

        /// <summary>
        /// 震動
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZD_Click(object sender, EventArgs e)
        {
            try
            {
                // 首字節是2說明是震動
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                socketSend.Send(buffer);
            }
            catch { }
        }

        /// <summary>
        /// 震動
        /// </summary>
        private void ZD()
        {
            //獲取當前窗體的坐標
            Point point = this.Location;
            //反復給窗體坐標復制一百次,達到震動的效果
            for (int i = 0; i < 100; i++)
            {
                this.Location = new Point(point.X - 5, point.Y - 5);
                this.Location = new Point(point.X + 5, point.Y + 5);
            }
            this.Location = point;
        }

    }
}
View Code

然后完畢,我覺得挺好的,跟大家分享一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM