zoukankan      html  css  js  c++  java
  • 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客户端连接
    "));
                }
                catch (Exception ex)
                {
                    richMsg.AppendText(string.Format("服务器启动失败,错误原因:{0}
    ", ex.Message));
                }
                AcceptUser();
            }
    
            /// <summary>
            /// 接受用户连接
            /// </summary>
            private void AcceptUser()
            {
                while (true)
                {
                    try
                    {
                        Socket nowClient = server.Accept();
                        userSocket[socketNum++] = nowClient;
                        userNum++;
                        richMsg.AppendText(string.Format("有新的用户接入,当前在线用户数:{0}
    ", userNum));
    
                        Thread nowThread = new Thread(new ParameterizedThreadStart(ReciveData));
                        nowThread.Start(nowClient);
                    }
                    catch (Exception ex)
                    {
                        richMsg.AppendText(string.Format("新用户接入失败:错误原因:{0}
    ", 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}
    ", str));
    
                        byte[] data = Encoding.UTF8.GetBytes(str);
                        SendAllUser(data, nowClient);
                    }
                    catch (Exception ex)
                    {
                        richMsg.AppendText(string.Format("接收用户消息失败:错误原因:{0}
    ", 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("消息转发成功!
    "));
                        }
                        catch (Exception ex)
                        {
                            userSocket[i] = userSocket[socketNum - 1];
                            socketNum--;
                            i--;
                            richMsg.AppendText(string.Format("用户断线,当前在线用户数:{0},断线原因:{1}
    ", socketNum, ex.Message));
                        }
                    }
                }
            }
        }
    
  • 相关阅读:
    ASP.NET提供文件下载函数
    web.config access数据库相对路径设置方法 for asp.net2.0
    MSDE安装后身份验证自动是windows验证,osql命令中修改为sqlserve身份验证或混合验证呢及注冊表修改方法
    关于ASP.NET IIS的注册:
    指定datagrid编辑框的宽度及相映属性(转)备用
    TransparentListBox
    在dll中使用FastReport会遇到以下内个问题
    值得学习一
    注册表恢复默认共享
    有关dnn的安装不成功问题
  • 原文地址:https://www.cnblogs.com/kinger906/p/3426836.html
Copyright © 2011-2022 走看看