在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# 简易聊天软件(socket编程)

C# 简易聊天软件(socket编程)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.62M
  • 下载次数:130
  • 浏览次数:802
  • 发布时间:2017-06-11
  • 实例类别:C#语言基础
  • 发 布 人:mili
  • 文件格式:.rar
  • 所需积分:2
 相关标签: 聊天 软件

实例介绍

【实例简介】

【实例截图】

【核心代码】


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

namespace SyncChatServer//================================服务器
{
    public partial class Form1 : Form
    {
        //保存用户列表
        private List<User> userList = new List<User>();     
        //监听socket  
        private Socket myListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        private bool isNormalExit = false;
        //端口号
        private static int myprot = 8889;
        //用户人数
        private static int usercount = 0;

        public Form1()
        {
            InitializeComponent();
            button2.Enabled=false;
            IPEndPoint ep;
            
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            try
            {
                myListener.Bind(new IPEndPoint(ip, myprot));
                richTextBox1.AppendText("主机IP:"   ip.ToString()   "\n");
            }
            catch {
                richTextBox1.AppendText("绑定失败");
            }
            //===================================================   
            
        }
        //-------------------------------------------向窗口输出信息
        private delegate void buttu_richBoxDelegate(string message);
        private void  buttu_richBox(string message)
        {
            richTextBox1.AppendText(message "\n");
        }
        //=======================================================
        //-------------------------------------------------------监听按键
        private void button1_Click(object sender, EventArgs e)
        {
            isNormalExit = false;
            buttu_richBoxDelegate d=buttu_richBox;
           try
           {
            myListener.Listen(10);
               richTextBox1.Invoke(d,"成功监听.");

           }catch{
               richTextBox1.Invoke(d,"监听失败。");
           }
            Thread mhThread=new Thread(ListenClientConnect);
            mhThread.IsBackground=true;
            mhThread.Start();
            button1.Enabled=false;
            button2.Enabled=true;
        }
        //=======================================================
        //-------------------------------------------------------监听事件
        private void ListenClientConnect()
        {
            Socket newClient =null;
            while(isNormalExit==false)
            {
                try
                {
                    newClient=myListener.Accept();
                    if (isNormalExit == true)
                    { 
                        newClient.Close();
                        usercount = 0;
                        UserCount(usercount);
                        break;
                    }
                }
                catch
                {
                    break ;
                }
                User user = new User(newClient);
                Thread threadReceive = new Thread(ReceiveData);
                threadReceive.IsBackground=true;
                threadReceive.Start(user);
                 UserCount(  usercount);
            }
        }
        //=======================================================
        //-------------------------------------------------------接收信息函数
        private void ReceiveData(object userState)
        {
            User user =(User)userState;
            Socket client=user.client;
            byte[] result=new byte[2048];
            string receiveString = null;
            int receiveNumber;
            while(isNormalExit==false)
            {
                
                try
                {
                     receiveNumber = client.Receive(result);
                     receiveString=Encoding.UTF8.GetString(result,0,receiveNumber);
                     //sendMessageTorichBox(receiveString);
                }
                catch
                {
                    if(isNormalExit==false)
                    {
                        sendMessageTorichBox("用户" user.username "已经退出!");
                        RemoveUser(user);
                    }
                    break;
                }

                string[] splitString =receiveString.Split(',');
                switch(splitString[0].ToLower())
                {
                    case "login":
                        user.username=splitString[1];
                        user.ip = splitString[2];
                        user.port = int.Parse(splitString[3]);
                        userList.Add(user);
                        AddItemToListBox(user.username);
                        sendToAllClient(user,receiveString);
                        FirstLogin(user);
                        
                        break;
                    case "logout":
                        DeletItemInListBox(user.username);
                        sendToAllClient(user,receiveString);
                        RemoveUser(user);
                        UserCount(--usercount);
                        break;
                    case "talk":
                        multMessage(user,receiveString);
                        break;
                    default:
                        sendMessageTorichBox("不知道什么意思!");
                        break;
                }
            }
        }
        //=============================================================
        private void multMessage(User user,String receiveString)
        {
            string[] splitString = receiveString.Split(',');
            for(int i=1;i<splitString.Length;i=i 3)
            {
                sendMessageTorichBox(string.Format("[{0}] 对 [{1}] 说:", user.username, splitString[i])   splitString[i 1]);
                foreach (User target in userList)
                {
                    if (target.username == splitString[i] && user.username != splitString[i])
                    {
                        SendToClient(target, "talk,"   user.username   ","   splitString[i 1]);
                        break;
                    }
                }
            }
        }
        //=============================================================
        private void SendToClient(User user,string message)
        {
            button_richBoxDelegate d=button_richBox;
            
            Socket socket=user.client;
            try
            {
                socket.Send(Encoding.UTF8.GetBytes(message));
            }
            catch
            {
                richTextBox1.Invoke(d,"发送信息失效。");
            }
        }

        private void sendToAllClient(User user,string message)
        {
            string command =message.Split(',')[0].ToLower();
            if(command=="login")
            {
                for(int i=0;i<userList.Count;i  )
                {
                    SendToClient(userList[i],message ",");
                
                }
            }
            else if(command=="logout")
            {
                for(int i=0;i<userList.Count;i  )
                {
                    if(userList[i].username!=user.username)
                    {
                        SendToClient(userList[i],message);
                    }
                }
            }
        }

        private void FirstLogin(User user)
        {   
            for (int i = 0; i < userList.Count; i  )
            {
                
                if(userList[i].username!=user.username)
                {
                    SendToClient(user,"login," userList[i].username "," userList[i].ip "," userList[i].port ",");
                }
            }
        }
        private delegate void UserCountDelegate(object obj);
        private void UserCount(object obj)
        {

            UserCountDelegate d = userCountFunction;
            label3.Invoke(d,obj);
        }
        private void userCountFunction(object obj)
        {
             label3.Text = (int)obj " 人";
        }
        private void RemoveUser(User user)
        {
            userList.Remove(user);
            user.Close();

        }

        private delegate void button_richBoxDelegate(string str);
        private void sendMessageTorichBox(string str)
        {
            button_richBoxDelegate d=button_richBox;
            richTextBox1.Invoke(d,str);
        }
        private void  button_richBox(string str)
        {
            richTextBox1.AppendText(str "\n");
        }
        private delegate void DeletItem_ListBoxDelegate(string str);
        private void DeletItemInListBox(string str)
        {
            DeletItem_ListBoxDelegate d = DeletItem_ListBox;
            listBox1.Invoke(d,str);
        }
        private void DeletItem_ListBox(string str)
        {
            listBox1.Items.Remove(str);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            listBox1.ClearSelected();
 
        }
        private delegate void AddItem_ListBoxDelegate(string str);
        
        private void AddItemToListBox(string str)
        {
            AddItem_ListBoxDelegate d=AddItem_ListBox;
            listBox1.Invoke(d,str);
        }
        private void AddItem_ListBox(string str)
        {
            listBox1.Items.Add(str);
            listBox1.SelectedIndex=listBox1.Items.Count-1;
            listBox1.ClearSelected();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sendMessageTorichBox("正在停止服务器,并依次使用户退出!");
            isNormalExit=true;
            for(int i=userList.Count-1;i>=0;i--)
            {
                userList[i].client.Close();
                RemoveUser(userList[i]);
            }
            //myListener.Shutdown(SocketShutdown.Both);
            //myListener.Close();
            button1.Enabled=true;
            button2.Enabled=false;
            CloseConnect();
            //mhThread.Join();
        }
        private delegate void  AddrichTextBox1MassageDelegate(string str);
        private void sendrichTextBox1Massage(string str)
        {
            richTextBox1.AppendText(str "\n");
        }
        private void button3_Click(object sender, EventArgs e)
        {
            AddrichTextBox1MassageDelegate d = sendrichTextBox1Massage;
            if (listBox1.SelectedIndex != -1)
            {
                //SendMessage("talk,"   listBox1.SelectedItem   ","   textBox2.Text);
                //----------------------------------------------------
                if (listBox1.Items.Count > 0)
                {
                    for (int i = 0; i < listBox1.SelectedItems.Count; i  )
                    {
                        for (int j = 0; j < userList.Count; j  )
                        {
                            if (userList[j].username == listBox1.SelectedItems[i].ToString())
                            {
                                SendToClient(userList[j], "talk,Server,"   textBox1.Text);
                                richTextBox1.Invoke(d, "[Server] 对 ["   userList[j].username   "]说:"   textBox1.Text);
                                
                            }
                        }
                        //SendMessage("talk,"   listBox1.SelectedItems[i].ToString()   ","   textBox2.Text);
                        //richTextBox1.Invoke(d, "我对["   listBox1.SelectedItems[i].ToString()   "]说:"   textBox2.Text);
                    }
                }
                //----------------------------------------------------

                /*for(int i=0;i<userList.Count;i  )
                {
                    if(userList[i].username == listBox1.SelectedItem.ToString())
                    {
                      SendToClient(userList[i], "talk,Server,"   textBox1.Text);
                      richTextBox1.Invoke(d, "[Server] 对 [" userList[i].username "]说:" textBox1.Text);
                      textBox1.Clear();
                    }
                }*/
                  textBox1.Clear();
            }
            else
            {
                sendrichTextBox1Massage("请先选择一个对话者.");
            }
        }

        private delegate void ClearListBoxItemDelegate();
        private void CloseConnect()
        {
            ClearListBoxItemDelegate d1 = ClearListBoxItemFunction;
            listBox1.Invoke(d1);
            usercount = 0;
            UserCount(usercount);
        }
        private void ClearListBoxItemFunction()
        {
            listBox1.Items.Clear();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}


标签: 聊天 软件

实例下载地址

C# 简易聊天软件(socket编程)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

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

查看所有1条评论>>

小贴士

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

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

关于好例子网

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

;
报警