用Socket及window service 调度多台服务器

    最近的项目中遇到了,使用多台服务器,多个客户端来运行一个分布式存储、计算应用程序。总是打开远程连接太过于麻烦且网速慢的原因,所以写一个的调度的程序。

情况如下:

   环境:N台Server,N台Client,一台调度机子

   功能:

       (1),在调度机上通过命令行连接远程机器,并传入相应的指令

       (2),客户端通过Socket监听调度机指点的端口

       (3) ,接受到指令后,客户端用process class执行批处理文件

   布署:

      在被调度机器上将程序的server端添到windows service中,可以使用如下命令(批处理)

 1 set BIN_PATH=D:\**\bin\Debug
 2 set SERVICE_NAME=服务名称
 3 set SERVICE_Description=描述
 4 
 5 cd /"%BIN_PATH%"
 6 
 7 sc stop %SERVICE_NAME%
 8 sc delete %SERVICE_NAME%
 9 
10 sc create %SERVICE_NAME% binpath= "%cd%\server.exe" start= auto
11 sc description %SERVICE_NAME% "%SERVICE_Description%"
12 sc start %SERVICE_NAME%
13 

14 cmd 


Client side代码: 

 1 public static void StartClient()
 2        {
 3            string strParamater = TArgs.MachineList + ";" + TArgs.CommandName + ";" + TArgs.ProcessName + ";" + TArgs.ProgramPath;
 4
 5            // Data buffer for incoming data.
 6            byte[] bytes = new byte[1024];
 7
 8            // Connect to a remote device.
 9            try
10            {
11
12                IPHostEntry ipHostInfo = null;
13                List<IPAddress> iplist = new List<IPAddress>();
14
15                string strHostName = TArgs.MachineList;
16                string[] iArrHostName = strHostName.Split(',');
17                for (int i = 0; i < iArrHostName.Length; i++)
18                {
19                    ipHostInfo = Dns.Resolve(iArrHostName[i]);
20                    iplist.Add(ipHostInfo.AddressList[0]);
21                }

22
23                for (int i = 0; i < iplist.Count; i++)
24                {
25                    // Connect the socket to the remote endpoint. Catch any errors.
26                    try
27                    {
28                        Console.WriteLine("Socket connected to {0}", iArrHostName[i].ToString());
29
30                        // Create a TCP/IP  socket.
31                        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
32
33                        sender.Connect(iplist[i], 11000);
34                                               
35                        // Encode the data string into a byte array.
36                        byte[] msg = Encoding.ASCII.GetBytes( strParamater + "<EOF>");
37
38                        // Send the data through the socket.
39                        int bytesSent = sender.Send(msg);
40
41                        // Receive the response from the remote device.
42                        int bytesRec = sender.Receive(bytes);
43                        Console.WriteLine("Echoed string = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
44
45                        // Release the socket.
46                        sender.Shutdown(SocketShutdown.Both);
47                        sender.Close();
48
49                        Console.WriteLine("successful!");
50                        Console.WriteLine("");
51
52                    }

53                    catch (ArgumentNullException ane)
54                    {
55                        Console.WriteLine("failed!");
56                        Console.WriteLine("{1};ArgumentNullException : {0}", ane.ToString(), iplist[i].ToString());
57                        Console.WriteLine("");
58                    }

59                    catch (SocketException se)
60                    {
61                        Console.WriteLine("failed!");
62                        Console.WriteLine("{1};SocketException : {0}", se.Message,iplist[i].ToString() );
63                        Console.WriteLine("");
64                        //Console.WriteLine("SocketException : {0}",se.ToString());
65
66                    }

67                    catch (Exception e)
68                    {
69                        Console.WriteLine("failed!");
70                        Console.WriteLine("{1};Unexpected exception : {0}", e.ToString(),iplist[i].ToString() );
71                        Console.WriteLine("");
72                    }

73                }

74
75            }

76            catch (Exception e)
77            {
78                Console.WriteLine(e.ToString());
79            }

80        }

81        static InputArgs TArgs = new InputArgs();
82
83        public static int Main(String[] args)
84        {
85            if (!Parser.ParseArgumentsWithUsage(args, TArgs))
86            {
87                return 0;
88            }

89
90            StartClient();
91            return 0;

92        }

 1 class InputArgs
 2    {
 3        [Argument(ArgumentType.Required, LongName = "MachineList", ShortName = "ML", HelpText = "machine list,such as server1,server2")]
 4        public string MachineList = string.Empty;
 5
 6        [Argument(ArgumentType.Required, LongName = "CommandName", ShortName = "CN", HelpText = "Command name ,it cantain create,restart,delete,stop,killClientAll, strartClient and other(path+file)")]
 7        public string CommandName = string.Empty;
 8
 9        [Argument(ArgumentType.AtMostOnce, LongName = "ProcessName", ShortName = "PN", HelpText = "process name,which need to kill")]
10        public string ProcessName = string.Empty;
11
12        [Argument(ArgumentType.AtMostOnce, LongName = "ProgramPath", ShortName = "PP", HelpText = "program path which need to start")]
13        public string ProgramPath = string.Empty;
14
15       
16    }

 Server side代码:

  1 // Incoming data from the client.
  2        public static string data = null;
  3
  4        public static void StartListening()
  5        {
  6            // Data buffer for incoming data.
  7            byte[] bytes = new Byte[1024];
  8
  9            IPAddress ipAddress = IPAddress.Any; 
 10            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
 11
 12            // Create a TCP/IP socket.
 13            Socket listener = new Socket(AddressFamily.InterNetwork,
 14                SocketType.Stream, ProtocolType.Tcp);
 15
 16            string istrLocalHostName = string.Empty;
 17            Socket handler = null
 18
 19            // Bind the socket to the local endpoint and 
 20            // listen for incoming connections.
 21            try
 22            {
 23                listener.Bind(localEndPoint);
 24                listener.Listen(10);
 25
 26                // Start listening for connections.
 27                while (true)
 28                {
 29                    try
 30                    {
 31
 32                        Console.WriteLine("Waiting for a connection");
 33                        // Program is suspended while waiting for an incoming connection.
 34                        handler = listener.Accept();
 35                        data = null;
 36
 37                        // An incoming connection needs to be processed.
 38                        while (true)
 39                        {
 40                            bytes = new byte[1024];
 41                            int bytesRec = handler.Receive(bytes);
 42                            data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
 43                            if (data.IndexOf("<EOF>"> -1)
 44                            {
 45                                break;
 46                            }

 47                        }

 48
 49                        if (data != null)
 50                            data = data.Replace("<EOF>""");
 51
 52                        //information(machine list,command)
 53                        istrLocalHostName = Dns.GetHostName();
 54                        string[] strArrMachineList = data.Split(';')[0].Split(',');
 55
 56                        string strCmd = data.Split(';')[1];
 57                        bool bltemp = false;
 58                        for (int i = 0; i < strArrMachineList.Length; i++)
 59                        {
 60                            if (strArrMachineList[i] == istrLocalHostName)
 61                                bltemp = true;
 62                        }

 63                        if (!bltemp)
 64                        {
 65                            Console.WriteLine("{0}""Not contain my hostname in list!");
 66                            return;
 67                        }

 68
 69                        //Handle the command
 70                        switch (strCmd)
 71                        {
 72                            case "create":
 73                                //create service with the path                                  
 74                                Process.Start("Service_Create.bat");
 75                                Console.WriteLine("create service, the path: {0}", strCmd);
 76
 77                                break;
 78                            case "restart":
 79                                Process.Start("Service_Restart.bat");
 80                                Console.WriteLine("restart the service,the path : {0}", strCmd);
 81                                break;
 82                            case "delete":
 83                                Process.Start("Service_Delete.bat");
 84                                Console.WriteLine("delete the service,the path : {0}", strCmd);
 85                                break;
 86                            case "stop":
 87                                Process.Start("Service_Stop.bat");
 88                                Console.WriteLine("stop the service,the path : {0}", strCmd);
 89                                break;
 90                            case "killClientAll":
 91                                string iProcessName = data.Split(';')[2];
 92                                Process[] proS = Process.GetProcessesByName(iProcessName);
 93                                for (int i = 0; i < proS.Length; i++)
 94                                {
 95                                    proS[i].Kill();
 96                                }

 97                                Console.WriteLine("kill process: {0}", iProcessName);
 98                                break;
 99                            case "strartClient":
100                                string iPath = data.Split(';')[3];
101                                Process.Start(iPath);
102                                Console.WriteLine("start program: {0}", iPath);
103                                break;
104
105                            default:
106                                if (data != null)
107                                {
108                                    Process.Start(data);
109                                    Console.WriteLine("excute a refered commmand : {0}", strCmd);
110                                }

111                                else
112                                    Console.WriteLine("Error: {0}""Don't get any command");
113                                break;
114                        }

115
116
117                        // Echo the data back to the client.
118                        byte[] msg = Encoding.ASCII.GetBytes("from " + istrLocalHostName);
119
120                        handler.Send(msg);
121                        handler.Shutdown(SocketShutdown.Both);
122                        handler.Close();
123                    }

124                    catch (Exception e)
125                    {
126                        Console.WriteLine(e.ToString());
127
128                        // Echo the data back to the client.
129                        byte[] msg = Encoding.ASCII.GetBytes("Exception:" + e.Message);
130
131                        handler.Send(msg);
132                        handler.Shutdown(SocketShutdown.Both);
133                        handler.Close();
134
135                    }

136                }

137
138            }

139            catch (Exception e)
140            {
141                Console.WriteLine(e.ToString());
142            }

143
144            Console.WriteLine("\nPress ENTER to continue");
145            Console.Read();
146
147        }

148
149        public static int Main(String[] args)
150        {
151            StartListening();
152            return 0;
153        }

调用client side的批处理

Code
原文地址:https://www.cnblogs.com/luyinghuai/p/1271620.html