在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → c#使用Socket创建简单聊天工具

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

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.10M
  • 下载次数:23
  • 浏览次数:222
  • 发布时间:2021-12-23
  • 实例类别:C#语言基础
  • 发 布 人:ruochen4267
  • 文件格式:.rar
  • 所需积分:5
 相关标签: Socket 服务器 客户端

实例介绍

【实例简介】c#使用Socket创建简单聊天工具

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

【实例截图】

from clipboardfrom clipboard

【核心代码】

  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


实例下载地址

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警