基本信息
源码名称:c#使用Socket创建简单聊天工具
源码大小:0.10M
文件格式:.rar
开发语言:C#
更新时间:2021-12-23
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

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

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

c#使用Socket创建简单聊天工具

  分别为服务器端和客户端,实时监听与信息发送

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Scoket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //拿到服务器的IP地址
                IPAddress ip = IPAddress.Any;//IPAddress.Parse(txtServer.Text);
                //创建端口号对象
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //监听(本机/服务器的ip地址和端口号)
                socketWatch.Bind(point);
                ShowMsg("监听成功");
                //设置最多同时监听的数量
                socketWatch.Listen(10);

                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch { }
        }
        //将远端的IP地址和Socket存入集合中
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        /// <summary>
        /// 等待客户端连接 并创建与之通信用的Socket
        /// </summary>
        /// <param name="str"></param>
        Socket socketSend;
        void Listen(object o)
        {
            Socket socketWatch = o as Socket;           
            while (true)
            {
                try
                {
                    //等待客户端的连接 并创建一个负责通信的Socket
                    socketSend = socketWatch.Accept();//监听的socket接受远端连接创建负责通信的Socket
                    //ip:端口号:连接成功
                    //( socketSend.RemoteEndPoint.ToString()拿到远端来访问的ip和端口号)
                    ShowMsg(socketSend.RemoteEndPoint.ToString() ":" "连接成功");
                    //将远端的IP地址和Socket存入集合中
                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    cbo.Items.Add(socketSend.RemoteEndPoint.ToString());

                    //(远端发完消息后在这个循环里面监听Socket开启监听其他的设备,不能再发消息,所以封装写个函数)
                    ////客户端连接成功后,服务器应该接受客户端发来的消息
                    //byte[] buffer = new byte[1024 * 1024 * 5];
                    ////实际接收到的有效字节数
                    //int r = socketSend.Receive(buffer);                   
                    //string str = Encoding.UTF8.GetString(buffer, 0, r);
                    //ShowMsg(socketSend.RemoteEndPoint ":" str);


                    //开启一个新线程不停的接受客户端发送过来的消息
                    Thread th = new Thread(Recive);
                    th.IsBackground = true;
                    th.Start(socketSend);                                     
                }
                catch { }
              
            }
        }


        /// <summary>
        /// 服务器端不停接受客户端发来的消息
        /// </summary>
        /// <param name="o"></param>
        void Recive(object o )
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    //客户端连接成功后,服务器应该接受客户端发来的消息
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    //实际接收到的有效字节数
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    ShowMsg(socketSend.RemoteEndPoint ":" str);
                }
                catch
                { }
            }
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线程访问错误捕捉
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 服务器给客户端发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //自己做一个协议,如果在发送消息按钮下,第一位加0,发送文件按钮下,第一位加1,震动加2
        private void txtMsg_Click(object sender, EventArgs e)
        {
            string str= txtMsg.Text.Trim();
            byte[] buffer =Encoding.UTF8.GetBytes(str);
            List<byte> list = new List<byte>();
            list.Add(0);
            list.AddRange(buffer);
            byte[] newbuffer = list.ToArray();
            //获得给下拉框中被选择用户的ip
            string ip = cbo.SelectedItem.ToString();
            dicSocket[ip].Send(newbuffer);
            //socketSend.Send(buffer);
            txtMsg.Clear();
        }
        OpenFileDialog ofd = new OpenFileDialog();
        /// <summary>
        /// 选择要发送的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {            
            ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";
            ofd.Multiselect = false;
            ofd.Filter = "所有文件|*.*";
            ofd.ShowDialog();
            //获得选中文件的路径
            string str = ofd.FileName;
            //获得该路径下的文件名
            string filename = Path.GetFileName(str);
            txtwj.Text = filename;
        }
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            using (FileStream fsread = new FileStream(ofd.FileName, FileMode.OpenOrCreate, FileAccess.Read))
            {
                //while (true)//大文件传输问题,涉及到断点续传
                //{
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = fsread.Read(buffer, 0, buffer.Length);
                    //if(r==0)
                    //{
                    //    break;
                    //}
                    List<byte> list = new List<byte>();
                    list.Add(1);
                    list.AddRange(buffer);
                    byte[] newbuffer = list.ToArray();
                    try
                    {
                        //获得给下拉框中被选择用户的ip
                        string ip = cbo.SelectedItem.ToString();
                        dicSocket[ip].Send(newbuffer, 0, r 1, SocketFlags.None);
                    }
                    catch { }
                //}
                txtwj.Clear();
            }
        }
        /// <summary>
        /// 发送震动,让窗口在两个位置交换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[1];
            buffer[0] = 2;
            dicSocket[cbo.SelectedItem.ToString()].Send(buffer);
        }
    }


.
├── c#使用Socket创建简单连天工具
│   ├── 06、Server
│   │   ├── 06、Server.csproj
│   │   ├── App.config
│   │   ├── Form1.Designer.cs
│   │   ├── Form1.cs
│   │   ├── Form1.resx
│   │   ├── Program.cs
│   │   ├── Properties
│   │   │   ├── AssemblyInfo.cs
│   │   │   ├── Resources.Designer.cs
│   │   │   ├── Resources.resx
│   │   │   ├── Settings.Designer.cs
│   │   │   └── Settings.settings
│   │   ├── bin
│   │   │   ├── Debug
│   │   │   │   ├── 06、Server.exe
│   │   │   │   ├── 06、Server.exe.config
│   │   │   │   ├── 06、Server.pdb
│   │   │   │   ├── 06、Server.vshost.exe
│   │   │   │   ├── 06、Server.vshost.exe.config
│   │   │   │   └── 06、Server.vshost.exe.manifest
│   │   │   └── Release
│   │   └── obj
│   │       └── Debug
│   │           ├── 06、Server.csproj.FileListAbsolute.txt
│   │           ├── 06、Server.csproj.GenerateResource.Cache
│   │           ├── 06、Server.csprojResolveAssemblyReference.cache
│   │           ├── 06、Server.exe
│   │           ├── 06、Server.pdb
│   │           ├── DesignTimeResolveAssemblyReferences.cache
│   │           ├── DesignTimeResolveAssemblyReferencesInput.cache
│   │           ├── TempPE
│   │           ├── TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs
│   │           ├── TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs
│   │           ├── TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs
│   │           ├── _06_Server.Form1.resources
│   │           └── _06_Server.Properties.Resources.resources
│   └── 07、Client
│       ├── 07、Client.csproj
│       ├── App.config
│       ├── Form1.Designer.cs
│       ├── Form1.cs
│       ├── Form1.resx
│       ├── Program.cs
│       ├── Properties
│       │   ├── AssemblyInfo.cs
│       │   ├── Resources.Designer.cs
│       │   ├── Resources.resx
│       │   ├── Settings.Designer.cs
│       │   └── Settings.settings
│       ├── bin
│       │   ├── Debug
│       │   │   ├── 07、Client.exe
│       │   │   ├── 07、Client.exe.config
│       │   │   ├── 07、Client.pdb
│       │   │   ├── 07、Client.vshost.exe
│       │   │   ├── 07、Client.vshost.exe.config
│       │   │   └── 07、Client.vshost.exe.manifest
│       │   └── Release
│       └── obj
│           └── Debug
│               ├── 07、Client.csproj.FileListAbsolute.txt
│               ├── 07、Client.csproj.GenerateResource.Cache
│               ├── 07、Client.csprojResolveAssemblyReference.cache
│               ├── 07、Client.exe
│               ├── 07、Client.pdb
│               ├── DesignTimeResolveAssemblyReferences.cache
│               ├── DesignTimeResolveAssemblyReferencesInput.cache
│               ├── TempPE
│               ├── TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs
│               ├── TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs
│               ├── TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs
│               ├── _07_Client.Form1.resources
│               └── _07_Client.Properties.Resources.resources
└── 好例子网_c#使用Socket创建简单连天工具.rar

17 directories, 59 files