在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#网络编程 → c# 高性能 iocp服务端 示例源码

c# 高性能 iocp服务端 示例源码

C#网络编程

下载此实例
  • 开发语言:C#
  • 实例大小:0.11M
  • 下载次数:130
  • 浏览次数:1772
  • 发布时间:2017-12-28
  • 实例类别:C#网络编程
  • 发 布 人:pzg123
  • 文件格式:.rar
  • 所需积分:2
 相关标签: C# 服务器 服务 c IOC

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using IocpServer;
using IocpServer.AsyncSocketServer;

namespace IoServer
{
    public enum ProtocolFlag
    {
        None = 0,
        Add = 1,
        Remove = 2,
        Clear = 3
    }

    public partial class Form1 : Form
    {
        //主窗体
        public static Form1 mainform = null;
        //调试信息窗体
        public static MessageBOX messagelist;
        //server服务
        public static IServerSocket serversocket;

        //用户列表 第一个参数是 ConnectID,第二个 参数是用户名
        public static Dictionary<string, string> userlistdata = new Dictionary<string, string>();

        //获取主窗体
        public static Form1 GetMainForm()
        {
            if (mainform != null)
            {
                return mainform;
            }
            return null;
        }

        //构造函数
        public  Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            Form1.mainform = this;
        }

        public static void Debug(string message)
        {
            if (messagelist != null)
            {
                messagelist.AddMessage(message);
            }
        }
        public static void DebugError(string message)
        {
            if (messagelist != null)
            {
                messagelist.AddMessage(message);
            }
        }

        public bool SetListBoxUser(string id, string user, ProtocolFlag flag)
        {
            try
            {
                lock (((ICollection)userlistdata).SyncRoot)
                {
                    string str = "";
                    switch (flag)
                    {
                        case ProtocolFlag.Add:
                            if (!userlistdata.TryGetValue(id, out str))
                            {
                                userlistdata.Add(id, user);
                                return true;
                            }
                            break;
                        case ProtocolFlag.Remove:
                            if (userlistdata.TryGetValue(id, out str))
                            {
                                userlistdata.Remove(id);
                                return true;
                            }
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                Debug("异常来自于 Form1.cs SetListBoxUser  "   ex.ToString());
                return false;
            }
        }

        public void ShowData(Dictionary<string, string> userdata)
        {
            try
            {
                listBox1.Items.Clear();
                foreach (KeyValuePair<string, string> pair in userdata)
                {
                    obj1 obj = new obj1();
                    obj.username = pair.Value;
                    obj.connectid = pair.Key;
                    listBox1.Items.Add(obj);
                    //listBox1.Items.Add(pair.Value);
                }
                if (userdata.Count > 0) listBox1.SelectedIndex = userdata.Count - 1;
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs ShowData  "   ex.ToString());
            }
        }

        /// <summary>
        /// 接受到数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="toker"></param>
        public void clientread(object sender, IocpServer.AsyncUserToken toker)
        {
            try
            {
                byte[] destArray = new byte[toker.BytesReceived];// 目的字节数组
                Array.Copy(toker.ReceiveBuffer, toker.Offset   2, destArray, 0, toker.BytesReceived - 2);
                string str = System.Text.Encoding.UTF8.GetString(destArray);
                string text = str.Substring(0, toker.BytesReceived - 2);
                //string text = str;
                //string msg = "接收到用户{0}的消息:{1}";
                //msg = string.Format(msg,toker.ConnectionId.ToString(), text);
                //Debug("READ   "   msg);

                if (SetListBoxUser(toker.ConnectionId, text, ProtocolFlag.Add) == true)
                {
                    ShowData(userlistdata);
                    this.toolStripStatusLabel1.Text = "添加新用户:"   text;
                    destArray[toker.BytesReceived - 2] = 0x38;
                    destArray[toker.BytesReceived - 1] = 0x38;
                    Form1.serversocket.Send(toker.ConnectionId, destArray);
                }
                else
                {
                    destArray[toker.BytesReceived - 2] = 0x4E;
                    destArray[toker.BytesReceived - 1] = 0x6F;
                    Form1.serversocket.Send(toker.ConnectionId, destArray);
                }

                //if (str == "login")
                //{
                //    if (SetListBoxUser(toker.ConnectionId, str, ProtocolFlag.Add) == true)
                //    {
                //        ShowData(userlistdata);
                //        this.toolStripStatusLabel1.Text = "添加新用户:"   str;
                //    }
                //}
                //else if (text == "start")
                //{
                //    text = text.Substring(6, text.Length - 7);
                //    //由于我们是以逗号分隔的,所以用户提交的逗号,需要替换好,我们替换为了'.'号
                //    text=text.Replace(',','.');
                //    userlistdata.Add(toker.ConnectionId, text);
                //    ShowData(userlistdata);
                //}
            }
            catch (Exception ex)
            {

                DebugError("异常来自于:Form1.cs 353行   "   ex.ToString());
            }
            System.Threading.Thread.Sleep(10);
        }

        /// <summary>
        /// 断开客户端事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="toker"></param>
        public void disconnect(object sender, IocpServer.AsyncUserToken toker)
        {
            try
            {
                DelClient(toker.ConnectionId);
                ShowData(userlistdata);
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 From1.cs disconnect  "   ex.ToString());
            }
        }

        //添加一个用户
        public static void AddUser(string connectid,AsyncUserToken token)
        {
            try
            {
                Form1 form = Form1.GetMainForm();
                if (form != null)
                {
                    form.toolStripStatusLabel1.Text = "一个新的连接";
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于:Form1.cs AddUser  " ex.ToString());
            }
        }

        /// <summary>
        /// 删除断开的连接
        /// </summary>
        /// <param name="connectid"></param>
        public void DelClient(string connectid)
        {
            //string msg = "一个用户{0}离开!当前有{1}个用户!";
            //msg = string.Format(msg, connectid,serversocket.NumConnectedSockets);
            //Debug("DIS  "   msg);
            try
            {
                Form1 form = Form1.GetMainForm();
                if (form != null)
                {
                    form.toolStripStatusLabel1.Text = "一个连接断开";
                }
                if (SetListBoxUser(connectid, "", ProtocolFlag.Remove) == true)
                    ShowData(userlistdata);
            }
            catch (Exception ex)
            {
                DebugError("异常来自于: Form1.cs DelClient  "   ex.ToString());
            }
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        private void StartServer()
        {
            try
            {
                int count = 0;
                if (!int.TryParse(textBox1.Text, out count))
                {
                    MessageBox.Show("连接数量错误!请重新填写!");
                    return;
                }
                int buffersize = 0;
                if (!int.TryParse(textBox2.Text, out buffersize))
                {
                    MessageBox.Show("缓冲区填写错误!请重新填写!");
                    return;
                }
                serversocket = new IServerSocket(count, buffersize);
                serversocket.Init();
                int port = 0;
                if (!int.TryParse(textBox3.Text, out port))
                {
                    MessageBox.Show("端口填写错误,请重新填写!");
                    return;
                }
                serversocket.Start(port);
                serversocket.OnClientRead  = new EventHandler<IocpServer.AsyncUserToken>(clientread);
                serversocket.OnClientDisconnect  = new EventHandler<IocpServer.AsyncUserToken>(disconnect);
            }
            catch (Exception ex)
            {
                DebugError("服务端启动失败......! 异常来自于 Form1.cs StartServer  " ex.ToString());
            }
        }

        //服务器启动
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = true;
            //不断获取当前连接数
            timer1.Enabled = true;
            if (checkBox1.Checked)
            {
                if (messagelist == null)
                {
                    messagelist = new MessageBOX(this);
                }
                messagelist.Show();
            }
            userlistdata.Clear();
            listBox1.Items.Clear();
            StartServer();
            this.toolStripStatusLabel1.Text = "服务器启动成功......!";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "服务端已经停止......!";
            button2.Enabled = false;
            button1.Enabled = true;
            serversocket.Shutdown();
        }

        /// <summary>
        /// 单独给某个用户发送消息,或者群发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //要发送的数据
            string text = textBox4.Text;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
            //群发
            if (checkBox2.Checked)
            {
                foreach (KeyValuePair<string, string> temp in userlistdata)
                {
                    try
                    {
                        Form1.serversocket.Send(temp.Key.ToString(), data);
                    }
                    catch (Exception ex)
                    {
                        Form1.DebugError(ex.ToString());
                    }
                }
                return;
            }
            int index = this.listBox1.SelectedIndex;
            if (index >= 0 && index < this.listBox1.Items.Count)
            {
                obj1 user = (obj1)this.listBox1.SelectedItem;
                serversocket.Send(user.connectid, data);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serversocket != null)
            {
                label6.Text = serversocket.NumConnectedSockets.ToString();
               
            }
            label10.Text = listBox1.Items.Count.ToString();
        }

        //开启和关闭调试窗口
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (messagelist == null)
                {
                    messagelist = new MessageBOX(this);
                    messagelist.Show();
                }
            }
            else
            {
                if (messagelist != null)
                {
                    messagelist.Close();
                    messagelist = null;
                }
            }
        }
        public void SetCheckBox(bool flag)
        {
            if (flag)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }
        }
        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("作者:梦想之家2工作室 阿龙(qq:1357098586,群:63438968)");
        }

        /// <summary>
        /// 搜索用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string findname = textBox5.Text;
            if (findname == "")
            {
                return;
            }
            else
            {
                int index = listBox1.FindString(findname);
                if (index > 0 && index <= listBox1.Items.Count)  
                    listBox1.SetSelected(index, true);
            }
        }

        /// <summary>
        /// 剔除一个用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            obj1 obj = (obj1)listBox1.SelectedItem;
            if (obj != null)
            {
                serversocket.Disconnect(obj.connectid);
            }
        }

    }
    public class obj1
    {
        public string username;
        public string connectid;
        public override string ToString()
        {
            return username;
        }
    }
}

标签: C# 服务器 服务 c IOC

网友评论

发表评论

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

查看所有1条评论>>

小贴士

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

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

关于好例子网

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

;
报警