• 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:UsersAdministratorDesktop";
                            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 + "
    ");
            }
    
            /// <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:UsersAdministratorDesktop";
                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:UsersAdministratorDesktop";
                            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 + "
    ");
            }
    
            /// <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:UsersAdministratorDesktop";
                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

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

  • 相关阅读:
    python Exception中的raise、assert
    python循环语句与其他编程语言不同之处
    【转】最大似然估计
    尝试发表代码
    奇异分解(SVD)
    Python学习笔记3-string
    梯度下降法
    前后端分离
    Trie树
    HashMap的工作原理以及代码实现,为什么要转换成红黑树?
  • 原文地址:https://www.cnblogs.com/aijiao/p/10467598.html
Copyright © 2020-2023  润新知