C#使用SuperSocket(WPF版)

W P F 使用 S u p e r S o c k e t WPF使用SuperSocket WPF使用SuperSocket

通过百度网盘分享的文件:SuperSocket
链接:https://pan.baidu.com/s/1u-FI7M9wUcY9QRDkkFEAug?pwd=1234
提取码:1234

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

一 服务器接收客户端数据

在客户端输入数字1后,一定要按下回车键才能点【发送数据】按钮,因为SuperSocket规定客户端给服务器发送的报文以"\r\n"为结束符

 1.创建一个AppServer实例
 2.安装和监听端口
 3.启动AppServer实例
 4.绑定SuperSocket的三个事件 ,连接事件,接收事件,关闭事件
 5.结束AppServer实例
using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Collections.Specialized.BitVector32;

namespace 通讯测试SuperSocket
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            // 1.创建一个AppServer实例
            var appServer = new AppServer();

            // 2.安装和监听端口
            if (!appServer.Setup(2021)) // Setup with listening port
            {
                MessageBox.Show("Failed to Setup!");
                return;
            }


            // 3.启动AppServer实例
            if (!appServer.Start())  //Try to start the appServer
            {
                MessageBox.Show("Failed to start!");
               
                return;
            }
            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            // 4. 绑定SuperSocket的三个事件 ,连接事件,接收事件,关闭事件
            appServer.NewSessionConnected += appServer_NewSessionConnected; //连接事件
            appServer.NewRequestReceived += appServer_NewRequestReceived;   //接收事件
            appServer.SessionClosed += appServer_SessionClosed;             //关闭事件


            MessageBox.Show("已运行!  ");
            // 5.结束AppServer实例
            // appServer.Stop();


        }

        /// <summary>
        /// 连接事件
        /// </summary>
        /// <param name="session"></param>
        static void appServer_NewSessionConnected(AppSession session)
        {
            MessageBox.Show("已连接!  " + session.RemoteEndPoint);
        }

        /// <summary>
        /// 接收事件
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
        {
            var key = requestInfo.Key;
            var body = requestInfo.Body;

            switch (key)
            {
                case "a":
                    MessageBox.Show("收到a");
                    break;
                case "b":
                    MessageBox.Show("收到b");
                    break;
                case "c":
                    MessageBox.Show(body);
                    break;
            }
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        static void appServer_SessionClosed(AppSession session, CloseReason value)
        {
            string ipAddress_Close = session.RemoteEndPoint.ToString();
            MessageBox.Show("已关闭连接!  " + ipAddress_Close);



        }

    }
}

在这里插入图片描述


二 服务器给客户端发送数据

session.Send方法即可实现

using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Collections.Specialized.BitVector32;

namespace 通讯测试SuperSocket
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            // 1.创建一个AppServer实例
            var appServer = new AppServer();

            // 2.安装和监听端口
            if (!appServer.Setup(2021)) // Setup with listening port
            {
                MessageBox.Show("Failed to Setup!");
                return;
            }


            // 3.启动AppServer实例
            if (!appServer.Start())  //Try to start the appServer
            {
                MessageBox.Show("Failed to start!");
               
                return;
            }
            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            // 4. 绑定SuperSocket的三个事件 ,连接事件,接收事件,关闭事件
            appServer.NewSessionConnected += appServer_NewSessionConnected; //连接事件
            appServer.NewRequestReceived += appServer_NewRequestReceived;   //接收事件
            appServer.SessionClosed += appServer_SessionClosed;             //关闭事件


            MessageBox.Show("已运行!  ");
            // 5.结束AppServer实例
            // appServer.Stop();


        }

        /// <summary>
        /// 连接事件
        /// </summary>
        /// <param name="session"></param>
        static void appServer_NewSessionConnected(AppSession session)
        {
            MessageBox.Show("已连接!  " + session.RemoteEndPoint);
        }

        /// <summary>
        /// 接收事件
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
        {
            var key = requestInfo.Key;
            var body = requestInfo.Body;

            switch (key)
            {
                case "a":
                    MessageBox.Show("收到a");
                    session.Send("server Accepted a");
                    break;
                case "b":
                    MessageBox.Show("收到b");
                    session.Send("server Accepted b");
                    break;
                case "c":
                    MessageBox.Show(body);
                    session.Send("server Accepted c");
                    break;
            }
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        static void appServer_SessionClosed(AppSession session, CloseReason value)
        {
            string ipAddress_Close = session.RemoteEndPoint.ToString();
            MessageBox.Show("已关闭连接!  " + ipAddress_Close);



        }

    }
}

在这里插入图片描述

三 界面化

在这里插入图片描述

<Window x:Class="通讯测试SuperSocket.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:通讯测试SuperSocket"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <Grid>
        <TextBox x:Name="txtIp" HorizontalAlignment="Left" Margin="111,68,0,0" TextWrapping="Wrap" Text="127.0.0.1" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="txtPort" HorizontalAlignment="Left" Margin="315,68,0,0" TextWrapping="Wrap" Text="5000" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="txtSend"  HorizontalAlignment="Left" Margin="72,348,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="541" Height="36"/>
        <Button x:Name="btnStart" Content="开启监听" HorizontalAlignment="Left" Margin="479,61,0,0" VerticalAlignment="Top" Height="30" Width="96" Click="btnStart_Click"/>
        <ComboBox Name="comboBox_SocketList" HorizontalAlignment="Left" Margin="640,68,0,0" VerticalAlignment="Top" Width="120"/>
        <RichTextBox Name="richTextBox1" Margin="72,149,206,135">
            <FlowDocument>
                <Paragraph>
                    <Run Text=""/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
        <Button x:Name="btnSendData" Content="发送数据" HorizontalAlignment="Left" Margin="651,350,0,0" VerticalAlignment="Top" Height="34" Width="124" Click="btnSendData_Click_1"/>
        <Label Content="IP地址:" HorizontalAlignment="Left" Margin="55,64,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.78,-0.135" Width="51"/>
        <Label Content="端口号:" HorizontalAlignment="Left" Margin="259,66,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.78,-0.135" Width="51"/>
        <Label Content="客户端列表:" HorizontalAlignment="Left" Margin="640,38,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.78,-0.135" Width="108"/>

    </Grid>
</Window>

    
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace 通讯测试SuperSocket
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {

        AppServer appServer;


        string ipAddress_Connect;
        string ipAddress_Close;
        string ipAddress_Receive;

        //存储session和对应ip端口号的泛型集合
        Dictionary<string, AppSession> sessionList = new Dictionary<string, AppSession>();

        enum OperateType
        {
            Add = 1,    //添加
            Remove = 2  //移除
        }

        public Window1()
        {
            InitializeComponent();



        }

 //        1.创建一个AppServer实例
 //2.安装和监听端口
 //3.启动AppServer实例
 //4.绑定SuperSocket的三个事件 ,连接事件,接收事件,关闭事件
 //5.结束AppServer实例


        /// <summary>
        /// 开启监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            // 1.创建一个AppServer实例
            appServer = new AppServer();

            // 2.安装和监听端口
            if (!appServer.Setup(int.Parse(txtPort.Text)))
            {
                richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText("Failed to Setup" + "\r\n"); }));
                return;
            }
            //3.启动AppServer实例
            if (!appServer.Start())
            {
                richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText("Failed to Start" + "\r\n"); }));
                return;
            }
            else
            {
                richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText("开启监听" + "\r\n"); }));
            }

            //4.绑定SuperSocket的三个事件 ,连接事件,接收事件,关闭事件
            appServer.NewSessionConnected += appServer_NewSessionConnected; //连接事件
            appServer.NewRequestReceived += appServer_NewRequestReceived;   //接收事件
            appServer.SessionClosed += appServer_SessionClosed;             //关闭事件

        }



        /// <summary>
        /// 接收连接
        /// </summary>
        /// <param name="session"></param>
        void appServer_NewSessionConnected(AppSession session)
        {

            //获取远程客户端的ip端口号
            ipAddress_Connect = session.RemoteEndPoint.ToString();
            Combobox_Handle_ipAddress(ipAddress_Connect, OperateType.Add);
            sessionList.Add(ipAddress_Connect, session);
            richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText(ipAddress_Connect + "已连接!" + "\r\n"); }));
        }


        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            //requestInfo.Key 是请求的命令行用空格分隔开的第一部分
            //requestInfo.Parameters 是用空格分隔开的其余部分
            //requestInfo.Body 是出了请求头之外的所有内容

            ipAddress_Receive = session.RemoteEndPoint.ToString();
            richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText("收到:" + ipAddress_Receive + "数据: " + requestInfo.Key + " " + requestInfo.Body + "\r\n"); }));
        }


        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param> 
        /// 
        //static void appServer_SessionClosed(AppSession session, CloseReason value)
        void appServer_SessionClosed(AppSession session, SuperSocket.SocketBase.CloseReason value)
        {
            ipAddress_Close = session.RemoteEndPoint.ToString();
            Combobox_Handle_ipAddress(ipAddress_Close, OperateType.Remove);
            sessionList.Remove(ipAddress_Close);
            richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText(ipAddress_Close + "已关闭连接!" + "\r\n"); }));
        }

        /// <summary>
        /// 添加和移除客户端(combobox操作)
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="operateType">add 添加项/remove 移除项</param>
        private void Combobox_Handle_ipAddress(string ipAddress, OperateType operateType)
        {
            // 添加客户端
            if (operateType == OperateType.Add)
            {
                comboBox_SocketList.Dispatcher.Invoke(new Action(() => { comboBox_SocketList.Items.Add(ipAddress); }));
            }
            // 删除客户端
            if (operateType == OperateType.Remove)
            {
                comboBox_SocketList.Dispatcher.Invoke(new Action(() => { comboBox_SocketList.Items.Remove(ipAddress); }));
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendData_Click_1(object sender, RoutedEventArgs e)
        {
            //从客户端列获取想要发送数据的客户端的ip和端口号,然后从sessionList中获取对应session然后调用send()发送数据
            if (comboBox_SocketList.Items.Count != 0)
            {
                if (comboBox_SocketList.SelectedItem == null)
                {
                    MessageBox.Show("请选择一个客户端发送数据!");
                    return;
                }
                else
                {
                    sessionList[comboBox_SocketList.SelectedItem.ToString()].Send(txtSend.Text);
                }
            }
            else
            {
                richTextBox1.Dispatcher.Invoke(new Action(() => { richTextBox1.AppendText("当前没有正在连接的客户端!" + "\r\n"); }));
            }
        }
    }
}

四 项目化

4.1自定义AppSession类

AppSession 代表一个和客户端的逻辑连接,基于连接的操作应该放在该类之中。你可以用该类的实例发送数据到客户端,接收客户端发送的数据或者关闭连接。

使用方法:创建自定义类SocketSession,继承AppSession类并重写AppSession类的方法(注意:一个AppSession对象对应一个连接)

using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 通讯测试SuperSocket.Communicate
{
    /// <summary>  
    /// 自定义连接类SocketSession,继承AppSession,并传入到AppSession  
    /// </summary>  
    public class SocketSession : AppSession<SocketSession>
    {
        public override void Send(string message)
        {
            Console.WriteLine("发送消息:" + message);
            base.Send(message);
        }


        protected override void OnSessionStarted()
        {
            //输出客户端IP地址  
            Console.WriteLine(this.LocalEndPoint.Address.ToString());
            this.Send("Hello ! Welcome to SuperSocket Server!");
        }


        /// <summary>  
        /// 连接关闭  
        /// </summary>  
        /// <param name="reason"></param>  
        protected override void OnSessionClosed(CloseReason reason)
        {
            base.OnSessionClosed(reason);
        }


        protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
        {
            Console.WriteLine($"遇到未知的请求 Key:" + requestInfo.Key + $" Body:" + requestInfo.Body);
            base.HandleUnknownRequest(requestInfo);
        }

        /// <summary>  
        /// 捕捉异常并输出  
        /// </summary>  
        /// <param name="e"></param>  
        protected override void HandleException(Exception e)
        {
            this.Send("error: {0}", e.Message);
        }
    }
}

4.2 自定义AppServer类

AppServer 代表了监听客户端连接,承载TCP连接的服务器实例。理想情况下,我们可以通过AppServer实例获取任何你想要的客户端连接,服务器级别的操作和逻辑应该定义在此类之中。

使用方法:创建自定义类SocketServer,继承AppServer类并重写AppServer类的方法

using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace 通讯测试SuperSocket.Communicate
{
    public class SocketServer : AppServer<SocketSession>
    {
        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {

            MessageBox.Show("正在准备配置文件");
            return base.Setup(rootConfig, config);
        }

        protected override void OnStarted()
        {
         
            MessageBox.Show("服务已开始");
            base.OnStarted();
        }

        protected override void OnStopped()
        {

            MessageBox.Show("服务已停止");
            base.OnStopped();
        }


        /// <summary>  
        /// 输出新连接信息  
        /// </summary>  
        /// <param name="session"></param>  
        protected override void OnNewSessionConnected(SocketSession session)
        {
            base.OnNewSessionConnected(session);
            //输出客户端IP地址  
            MessageBox.Show("\r\n" + session.LocalEndPoint.Address.ToString() + ":连接");
           
        }


        /// <summary>  
        /// 输出断开连接信息  
        /// </summary>  
        /// <param name="session"></param>  
        /// <param name="reason"></param>  
        protected override void OnSessionClosed(SocketSession session, CloseReason reason)
        {
            base.OnSessionClosed(session, reason);
            MessageBox.Show("\r\n" + session.LocalEndPoint.Address.ToString() + ":断开连接");
   
        }
    }
}

4.3 使用Command

CommandA

using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 通讯测试SuperSocket.Communicate
{
    public class CommandA : CommandBase<SocketSession, StringRequestInfo>
    {
        public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo)
        {
            session.Send("CommandA Return:"+requestInfo.Body);
        }

    }
}

CommandB

using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 通讯测试SuperSocket.Communicate
{
    public class CommandB : CommandBase<SocketSession, StringRequestInfo>
    {
        public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo)
        {
            session.Send("CommandB Return:" + requestInfo.Body);
        }

    }
}

CommandC

using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 通讯测试SuperSocket.Communicate
{
    public class CommandC : CommandBase<SocketSession, StringRequestInfo>
    {
        public override void ExecuteCommand(SocketSession session, StringRequestInfo requestInfo)
        {
            session.Send("CommandC Return:" + requestInfo.Body);
        }

    }
}

4.4 配置App.config使用BootStrap启动SuperSocket

<?xml version="1.0" encoding="utf-8" ?>
<configuration>



	<configSections>
		<!--log 日志记录-->
		<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
		<!--SocketEngine-->
		<section name="superSocket" type="SuperSocket.SocketEngine.Configuration.SocketServiceConfig, SuperSocket.SocketEngine"/>
	</configSections>

	<!--服务信息描述,在window服务模式下的名称标识-->
	<appSettings>
		<add key="ServiceName" value="通讯测试SuperSocket"/>
		<add key="ServiceDescription" value="TestSuperSocket"/>
	</appSettings>

	<!--SuperSocket服务配置信息 serverType是项目的服务如我自定义的Socketserver-->
	<!--name: 实例名称
      serverType: 实例运行的AppServer类型
      ip: 侦听ip
      port: 侦听端口-->
	<superSocket>
		<servers>
			<!--textEncoding 编码方式"gb2312","utf-8" 默认是acii-->
			<server name="通讯测试SuperSocket" textEncoding="gb2312" serverType="通讯测试SuperSocket.Communicate.SocketServer,通讯测试SuperSocket"
			 ip="Any"
			 port="5001"
			 maxConnectionNumber="100">
			</server>
		</servers>
	</superSocket>
	
	
	
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
</configuration>
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace 通讯测试SuperSocket
{
    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
        
            var bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                
                MessageBox.Show("初始化失败!");
                return;
            }

            var result = bootstrap.Start();

            Console.WriteLine("服务正在启动: {0}!", result);

            if (result == StartResult.Failed)
            {

                MessageBox.Show("服务启动失败!");
                return;
            }


            //停止服务
            // appServer.Stop();
            //bootstrap.Stop();
            //Console.WriteLine("服务已停止!");
            //Console.ReadKey();


        }
    }
}

在这里插入图片描述

在这里插入图片描述


补充:不使用配置文件,直接使用代码启动

using DrVision.Log;
using SuperSocket.SocketBase.Config;
using System;
using System.Collections.Generic;
using System.Configuration;

namespace DrVision.Communicate
{
    /// <summary>
    /// TCP服务启动/关闭管理
    /// </summary>
    public class ClientService : IDisposable
    {
        #region 单实例类
        private ClientService()
        {

        }

        public static ClientService Instance
        {
            get
            {
                return Nested._instance;
            }
        }

        class Nested
        {
            static Nested()
            {

            }

            internal static readonly ClientService _instance = new ClientService();
        }
        #endregion

        /// <summary>
        /// TCP Server类对象
        /// </summary>
        private ClientServer appServer = new ClientServer();

        public List<ClientSession> lst = new List<ClientSession>();

        public void AddNewSession(ClientSession session)
        {
            lst.Add(session);
        }

        public void RemoveSession(ClientSession session)
        {
            lst.Remove(session);
        }

        #region 启动TCP服务器
        public bool StartService()
        {
            // 如果已经启动则不在重复启动
            if (appServer != null && appServer.State == SuperSocket.SocketBase.ServerState.Running)
                return true;

            // 从AppConfig读取配置
            ServerConfig config = ReadServerConfig();

            // 配置服务参数
            if (!appServer.Setup(config))
            {
                MTLogger.Error("TCP服务配置失败!");
                return false;
            }
            if (!appServer.Start())
            {
                MTLogger.Error("初始化服务失败!\n");
                return false;
            }

            return true;
        }

        private ServerConfig ReadServerConfig()
        {
            ServerConfig serverConfig = new ServerConfig()
            {
                Name = "TestServer",
                ServerTypeName = "TestServer",
                Ip = "Any",
                Port = 6001,
                ClearIdleSession = false,
                IdleSessionTimeOut = 6000000,
                ClearIdleSessionInterval = 9000000,
                MaxConnectionNumber = 2,
                MaxRequestLength = 10240,
            };
            
            // 获取Configuration对象
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                string serverName = config.AppSettings.Settings["serverName"].Value;
                if (string.IsNullOrEmpty(serverName))
                    serverName = "DrVisionServer";

                string serverTypeName = config.AppSettings.Settings["serverTypeName"].Value;
                if (string.IsNullOrEmpty(serverTypeName))
                    serverTypeName = "DrVisionServer";

                string ip = config.AppSettings.Settings["ip"].Value;
                if (string.IsNullOrEmpty(ip))
                    ip = "Any";

                int port = Convert.ToInt32(config.AppSettings.Settings["port"].Value);
                if (port > 65535)
                    port = 60001;

                bool ClearIdleSession = Convert.ToBoolean(config.AppSettings.Settings["ClearIdleSession"].Value);

                int ClearIdleSessionInterval = Convert.ToInt32(config.AppSettings.Settings["ClearIdleSessionInterval"].Value);
                if (ClearIdleSessionInterval < 0)
                    ClearIdleSessionInterval = 6000;

                int IdleSessionTimeOut = Convert.ToInt32(config.AppSettings.Settings["IdleSessionTimeOut"].Value);
                if (IdleSessionTimeOut < 0)
                    IdleSessionTimeOut = 9000;

                int MaxRequestLength = Convert.ToInt32(config.AppSettings.Settings["MaxRequestLength"].Value);
                if (MaxRequestLength < 0)
                    MaxRequestLength = 10240;

                int MaxConnectionNumber = Convert.ToInt32(config.AppSettings.Settings["MaxConnectionNumber"].Value);
                if (MaxConnectionNumber < 1)
                    MaxConnectionNumber = 2;

                serverConfig.Ip = ip;
                serverConfig.Port = port;
                serverConfig.Name = serverName;
                serverConfig.ServerTypeName = serverTypeName;
                serverConfig.ClearIdleSession = ClearIdleSession;
                serverConfig.IdleSessionTimeOut = IdleSessionTimeOut;
                serverConfig.ClearIdleSessionInterval = ClearIdleSessionInterval;
                serverConfig.MaxConnectionNumber = MaxConnectionNumber;
                serverConfig.MaxRequestLength = MaxRequestLength;
            }
            catch(Exception ex)
            {
                
            }
            
            return serverConfig;
        }

        #endregion

        #region 停止服务
        public void StopService()
        {
            appServer.Stop();
        }

        #endregion

        public void Dispose()
        {
            StopService();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值