WebChart网页局域网聊天系列(二):服务器结构及核心代码

    public partial class MainForm : Form
    {
        private Socket server;//服务器Socket
        private int userNum;//当前在线用户数
        private int socketNum;//当前socket数
        private Socket[] userSocket = new Socket[40];//存储用户socket

        public MainForm()
        {
            InitializeComponent();

            Thread startThread = new Thread(new ThreadStart(Listen));
            startThread.Start();
        }

        /// <summary>
        /// 监听
        /// </summary>
        private void Listen()
        {
            userNum = 0;
            socketNum = 0;

            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["serverIp"]), int.Parse(ConfigurationManager.AppSettings["serverPort"]));
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                server.Bind(iep);
                server.Listen(20);
                richMsg.AppendText(string.Format("服务器已启动,等待WEB客户端连接\r\n"));
            }
            catch (Exception ex)
            {
                richMsg.AppendText(string.Format("服务器启动失败,错误原因:{0}\r\n", ex.Message));
            }
            AcceptUser();
        }

        /// <summary>
        /// 接受用户连接
        /// </summary>
        private void AcceptUser()
        {
            while (true)
            {
                try
                {
                    Socket nowClient = server.Accept();
                    userSocket[socketNum++] = nowClient;
                    userNum++;
                    richMsg.AppendText(string.Format("有新的用户接入,当前在线用户数:{0}\r\n", userNum));

                    Thread nowThread = new Thread(new ParameterizedThreadStart(ReciveData));
                    nowThread.Start(nowClient);
                }
                catch (Exception ex)
                {
                    richMsg.AppendText(string.Format("新用户接入失败:错误原因:{0}\r\n", ex.Message));
                }
            }
        }

        /// <summary>
        /// 接收客户端发过来的消息
        /// </summary>
        /// <param name="client"></param>
        private void ReciveData(object client)
        {
            Socket nowClient = (Socket)client;
            while (true)
            {
                int res = 0;
                byte[] bytes = new byte[1024];
                try
                {
                    res = nowClient.Receive(bytes);
                    string str = Encoding.UTF8.GetString(bytes, 0, res);
                    richMsg.AppendText(string.Format("{0}\r\n", str));

                    byte[] data = Encoding.UTF8.GetBytes(str);
                    SendAllUser(data, nowClient);
                }
                catch (Exception ex)
                {
                    richMsg.AppendText(string.Format("接收用户消息失败:错误原因:{0}\r\n", ex.Message));
                }
            }
        }

        /// <summary>
        /// 转发给其他所有用户
        /// </summary>
        /// <param name="data"></param>
        /// <param name="nowClient"></param>
        private void SendAllUser(byte[] data,Socket nowClient)
        {
            if (userNum > 0)
            {
                for (int i = 0; i < socketNum; i++)
                {
                    if (userSocket[i].Equals(nowClient))
                        continue;
                    try
                    {
                        userSocket[i].Send(data);
                        richMsg.AppendText(string.Format("消息转发成功!\r\n"));
                    }
                    catch (Exception ex)
                    {
                        userSocket[i] = userSocket[socketNum - 1];
                        socketNum--;
                        i--;
                        richMsg.AppendText(string.Format("用户断线,当前在线用户数:{0},断线原因:{1}\r\n", socketNum, ex.Message));
                    }
                }
            }
        }
    }

 

posted on 2013-11-16 15:41  kingtiger  阅读(577)  评论(0编辑  收藏  举报

导航