• 大小: 0.53M
    文件类型: .zip
    金币: 1
    下载: 0 次
    发布日期: 2020-12-14
  • 语言: C#
  • 标签: 客户端  tcp  

资源简介


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

namespace SocketTCP
{
    //声明委托
    delegate void AddOnLineDelegate(string str, bool bl);

    //声明委托
    delegate void RecMsgDelegate(string str);

    public partial class FrmTCPServer : Form
    {
        public FrmTCPServer()
        {
            InitializeComponent();
            myAddOnline = AddOnline;
            myRcvMsg = RecMsg;
            myFileSave = FileSave;
        }

        //创建套接字
        Socket sock = null;

        //创建负责监听客户端连接的线程
        Thread threadListen = null;

        //创建URL与Socket的字典集合
        Dictionary<string, Socket> DicSocket = new Dictionary<string, Socket>();

        AddOnLineDelegate myAddOnline;

        RecMsgDelegate myRcvMsg;

        FileSaveDelegate myFileSave;

        #region 开始监听
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_StartServer_Click(object sender, EventArgs e)
        {
            //创建负责监听的套接字,注意其中参数:IPV4 字节流 TCP
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());

            //根据IPAddress以及端口号创建IPE对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));

            try
            {
                sock.Bind(endpoint);
                Invoke(myRcvMsg, "服务器开启成功!");
                MessageBox.Show("开启服务成功!", "打开服务");
            }
            catch (Exception ex)
            {
                MessageBox.Show("开启服务失败" ex.Message, "打开服务");
                return;
            }

            sock.Listen(10);

            threadListen = new Thread(ListenConnecting);
            threadListen.IsBackground = true;
            threadListen.Start();
            this.btn_StartServer.Enabled = false;
        }
        #endregion

        #region 监听线程
        /// <summary>
        /// 监听线程
        /// </summary>
        private void ListenConnecting()
        {
            while (true)
            {
                //一旦监听到一个客户端的连接,将会创建一个与该客户端连接的套接字
                Socket sockClient = sock.Accept();

                string client = sockClient.RemoteEndPoint.ToString();

                DicSocket.Add(client, sockClient);

                Invoke(myAddOnline, client, true);
                Invoke(myRcvMsg, client "上线了!");
                //开启接受线程
                Thread thr = new Thread(ReceiveMsg);
                thr.IsBackground = true;
                thr.Start(sockClient);

            }
        }
        #endregion

        #region 接收线程
        /// <summary>
        /// 接收线程
        /// </summary>
        /// <param name="sockClient"></param>
        private void ReceiveMsg(object sockClient)
        {
            Socket sckclient = sockClient as Socket;
            while (true)
            {
                //定义一个2M缓冲区
                byte[] arrMsgRec = new byte[1024 * 1024 * 2];

                int length = -1;

                try
                {
                    length = sckclient.Receive(arrMsgRec);
                }
                catch (Exception)
                {
                    string str = sckclient.RemoteEndPoint.ToString();
                    Invoke(myRcvMsg, str "下线了!");
                    //从列表中移除URL
                    Invoke(myAddOnline, str, false);
                    DicSocket.Remove(str);
                    break;
                }

                if (length == 0)
                {
                    string str = sckclient.RemoteEndPoint.ToString();
                    Invoke(myRcvMsg, str "下线了!");
                    //从列表中移除URL
                    Invoke(myAddOnline, str, false);
                    DicSocket.Remove(str);
                    break;
                }
                else
                {
                    if (arrMsgRec[0] == 0)
                    {
                        string strMsg = Encoding.UTF8.GetString(arrMsgRec, 1, length-1);
                        string Msg = "[接收]     " sckclient.RemoteEndPoint.ToString() "     " strMsg;
                        Invoke(myRcvMsg, Msg);
                    }
                    if (arrMsgRec[0] == 1)
                    {
                        Invoke(myFileSave, arrMsgRec,length);

                    }
                }
            }
        }
        #endregion

        #region 委托方法体
        private void AddOnline(string url, bool bl)
        {
            if (bl)
            {
                this.lbOnline.Items.Add(url);
            }
            else
            {
                this.lbOnline.Items.Remove(url);
            }
        }

        private void RecMsg(string str)
        {
            this.txt_Rcv.AppendText(str Environment.NewLine);
        }

        private void FileSave(byte[] bt, int length)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "word files(*.docx)|*.docx|txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string fileSavePath = sfd.FileName;

                    using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
                    {
                        fs.Write(bt, 1, length - 1);
                        Invoke(new Action(() => this.txt_Rcv.AppendText("[保存]     保存文件成功" fileSavePath Environment.NewLine)));
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存异常" ex.Message, "保存文件出现异常");
            }
        }

        #endregion

        #region 发送消息
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendToSingle_Click(object sender, EventArgs e)
        {
            string StrMsg = this.txt_Send.Text.Trim();
            byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);

            byte[] arrSend = new byte[arrMsg.Length 1];
            arrSend[0] = 0;
            Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);


            if (this.lbOnline.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择你要发送的对象!", "发送提示");
                return;
            }
            else
            {
                foreach (string item in this.lbOnline.SelectedItems)
                {
                    DicSocket[item].Send(arrSend);

                    string Msg = "[发送]     " item "     " StrMsg;

                    Invoke(myRcvMsg, Msg);
                }
            }
        }
        #endregion

        #region 群发消息
        /// <summary>
        /// 群发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendToAll_Click(object sender, EventArgs e)
        {
            string StrMsg = this.txt_Send.Text.Trim();
            byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);

            byte[] arrSend = new byte[arrMsg.Length 1];
            arrSend[0] = 0;
            Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);

            foreach (string item in this.DicSocket.Keys)
            {
                DicSocket[item].Send(arrSend);

                string Msg = "[发送]     " item "     " StrMsg;

                Invoke(myRcvMsg, Msg);
            }
            Invoke(myRcvMsg, "[群发]     群发完毕!");
        }
        #endregion

        #region 打开客户端
        /// <summary>
        /// 打开客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Client_Click(object sender, EventArgs e)
        {
            FrmTCPClient objFrm = new FrmTCPClient();
            objFrm.Show();
        }
        #endregion

        #region 选择文件
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = "D:\\";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                this.txt_SelectFile.Text = ofd.FileName;
            }
        }
        #endregion

        #region 发送文件
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SendFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_SelectFile.Text))
            {
                MessageBox.Show("请选择您要发送的文件!", "发送文件提示");
                return;
            }
            string online = this.lbOnline.Text.Trim();
            if (string.IsNullOrEmpty(online))
            {
                MessageBox.Show("请选择您要发送的对象!", "发送文件提示");
                return;
            }
            using (FileStream fs = new FileStream(txt_SelectFile.Text, FileMode.Open))
            {
                string filename = Path.GetFileName(txt_SelectFile.Text);
                string StrMsg = "发送文件为:" filename;
                byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);

                byte[] arrSend= new byte[arrMsg.Length 1];
                arrSend[0] =0;
                Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);

                DicSocket[online].Send(arrSend);

                byte[] arrfileSend = new byte[1024 * 1024 * 2];
                int length = fs.Read(arrfileSend, 0, arrfileSend.Length);

                byte[] arrfile = new byte[length 1];
                arrfile[0] = 1;
                Buffer.BlockCopy(arrfileSend, 0, arrfile, 1, length);
          
                DicSocket[online].Send(arrfile);
            }

        }
        #endregion

    }
}


资源截图

代码片段和文件信息

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

namespace SocketTCP
{
    delegate void FileSaveDelegate(byte[] btint length);
    public partial class FrmTCPClient : Form
    {
        public FrmTCPClient()
        {
            InitializeComponent();
            MyFileSave = FileSave;
        }

        //Socket对象
        Socket sockClient = null;

        //接收线程
        Thread thrClient = null;

        //运行标志位
        private bool IsRunning = true;

        //文件保存委托对象
        FileSaveDelegate MyFileSave

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----
     目录           0  2018-11-13 21:56  Socket\.vs\
     目录           0  2018-11-13 21:46  Socket\.vs\Socket\
     目录           0  2018-11-13 21:56  Socket\.vs\Socket\v15\
     目录           0  2018-11-13 21:46  Socket\.vs\Socket\v15\Server\
     目录           0  2018-11-13 21:56  Socket\.vs\Socket\v15\Server\sqlite3\
     目录           0  2018-11-13 21:56  Socket\.vs\SocketTCP\
     目录           0  2018-11-13 21:56  Socket\.vs\SocketTCP\v15\
     文件       53248  2020-04-09 21:29  Socket\.vs\SocketTCP\v15\.suo
     目录           0  2018-11-13 21:56  Socket\.vs\SocketTCP\v15\Server\
     目录           0  2018-11-13 21:56  Socket\.vs\SocketTCP\v15\Server\sqlite3\
     文件           0  2018-11-13 21:56  Socket\.vs\SocketTCP\v15\Server\sqlite3\db.lock
     文件      598016  2018-11-18 01:07  Socket\.vs\SocketTCP\v15\Server\sqlite3\storage.ide
     文件       32768  2020-04-09 21:28  Socket\.vs\SocketTCP\v15\Server\sqlite3\storage.ide-shm
     文件     4136512  2020-03-30 20:55  Socket\.vs\SocketTCP\v15\Server\sqlite3\storage.ide-wal
     目录           0  2020-04-11 22:34  Socket\Socket\
     文件         189  2018-11-13 21:46  Socket\Socket\App.config
     目录           0  2020-04-11 22:34  Socket\Socket\bin\
     目录           0  2020-04-11 22:34  Socket\Socket\bin\Debug\
     文件       22016  2020-04-05 23:11  Socket\Socket\bin\Debug\SocketTCP.exe
     文件         189  2018-11-13 21:46  Socket\Socket\bin\Debug\SocketTCP.exe.config
     文件       50688  2020-04-05 23:11  Socket\Socket\bin\Debug\SocketTCP.pdb
     目录           0  2018-11-13 21:46  Socket\Socket\bin\Release\
     文件        7712  2018-11-18 01:27  Socket\Socket\FrmTCPClient.cs
     文件        9972  2018-11-18 00:16  Socket\Socket\FrmTCPClient.Designer.cs
     文件        5817  2018-11-18 00:16  Socket\Socket\FrmTCPClient.resx
     文件       11255  2018-11-18 01:27  Socket\Socket\FrmTCPServer.cs
     文件       11514  2018-11-17 23:31  Socket\Socket\FrmTCPServer.Designer.cs
     文件        5817  2018-11-17 23:31  Socket\Socket\FrmTCPServer.resx
     目录           0  2018-11-13 21:46  Socket\Socket\obj\
     目录           0  2020-04-11 22:34  Socket\Socket\obj\Debug\
     文件        1443  2018-11-13 22:52  Socket\Socket\obj\Debug\DesignTimeResolveAssemblyReferences.cache
............此处省略26个文件信息

评论

共有 条评论