异常设计

异常设计

需求:

用C#写一个控制台程序监听服务器的8100端口,一旦发现该接口的请求则重启IIS,并将是否成功的消息返回给请求方

实现:

Program.cs
程序入口,组织逻辑
Shell.cs
执行命令行程序
Listener.cs 
监听8100端口
    class Program
    {
        static int port = 8100;
        static void Main(string[] args)
        {
            // 最外层异常,只是为了防止编程错误和未意料异常
            try
            {
                Func<String, bool> execute = (String s) =>
                {
                    // 最内层的异常处理,只处理启动iis失败的异常
                    try
                    {
                        Console.WriteLine("");
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                        String result = Shell.Execute("iisreset /restart");
                        Console.Write(result);
                        return true;
                    }
                    catch (Exception ex){
                        Console.Write("Command Error" + ex.Message);
                        return false;
                    }
                };

                Console.WriteLine("Bind Port " + port);
                Listener listener = new Listener(port);
                listener.Listen(execute);
            }
            catch (Exception ex) {
                Console.WriteLine("Abort: " + ex.Message);
            }
        }
    }
class Listener
{
    Socket socket;
    public Listener(int port) {
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Bind(endPoint);
        socket.Listen(0);
    }

    ~Listener() {
        socket.Close();
    }

    public void Listen(Func<String, bool> execute) {
        byte[] buffer = new byte[1024];
        while (true) {
            Socket requestSocket = null;
            // 只有通信异常才是“异常”,iis重启异常只能算作重启失败,记录就可以了
            try {
                requestSocket = socket.Accept();
                requestSocket.Receive(buffer);
                String requestString = Encoding.ASCII.GetString(buffer);
                String resultCode = execute(requestString) ? "OK" : "ERROR";
                requestSocket.Send(System.Text.Encoding.Default.GetBytes(resultCode));
            }
            catch (Exception ex) {
                Console.WriteLine("Socket Exception: " + ex.Message);
            }
            finally {
                if (requestSocket != null) {
                    requestSocket.Close();
                }
            }
        }
    }
}

Shell.cs

省略,主要功能是为了调用在命令行下能执行的程序,和我主题无关

lishujun

程序员一枚