基于Socket的server, client的简单实例

  基于Socket的server, client的简单实例,这个实例用来打开关闭服务器上的服务。下面贴上Server和Client类,ExecuteCMD类就不贴了。

1, 打开server批处理命令:

  
  
  
  
  1. :参数1:端口 参数2:Service name 
  2. java -jar EP400ProToolkitServer.jar 5678 GP_CLT_Service 

2, Server类:

  
  
  
  
  1. import java.io.BufferedReader; 
  2. import java.io.IOException; 
  3. import java.io.InputStreamReader; 
  4. import java.io.PrintWriter; 
  5. import java.net.ServerSocket; 
  6. import java.net.Socket; 
  7. import org.apache.log4j.Logger; 
  8. import org.apache.log4j.PropertyConfigurator; 
  9.  
  10. import com.mmm.ep400.toolkit.ExecuteCMD; 
  11.  
  12. public class RestartServer extends Thread{ 
  13.     private static Logger logger = Logger.getLogger(RestartServer.class.getName()); 
  14.     private Socket client; 
  15.     private String service; 
  16.      
  17.     public RestartServer(Socket c, String service) { 
  18.         this.client = c; 
  19.         this.service = service; 
  20.         logger.info("Accept new client: " + client.getInetAddress().getHostName() + "/" + 
  21.                 client.getInetAddress().getHostAddress() + ":" + String.valueOf(client.getPort())); 
  22.     } 
  23.      
  24.     public static void main(String[] args) throws IOException { 
  25.         int port = 0
  26.         String service = null
  27.         PropertyConfigurator.configure("log4j.properties"); 
  28.         if (args.length == 2){ 
  29.             logger.info("Bind port " + args[0]); 
  30.             logger.info("Work service " + args[1]); 
  31.             if(args[0].matches("[0-9]+")){ 
  32.                 port = Integer.parseInt(args[0]); 
  33.             } 
  34.             service = args[1].trim(); 
  35.         }        
  36.         if (port < 1024 || port > 65535 || service == null || service.equals("")){ 
  37.             logger.error("Please init the port between 1024 ~ 65535 and service name"); 
  38.             System.exit(MAX_PRIORITY); 
  39.         } 
  40.          
  41.         ServerSocket server = new ServerSocket(port); 
  42.         logger.info("Server started"); 
  43.         while (true) { 
  44.             // transfer location change Single User or Multi User 
  45.             RestartServer mu = new RestartServer(server.accept(), service); 
  46.             mu.start(); 
  47.         } 
  48.     } 
  49.  
  50.     public void run() { 
  51.         boolean closeServer = false
  52.         String availableCMD = "available commond: start, stop, restart, exit, clsv (close EP400Pro toolkit service)"
  53.         try { 
  54.             BufferedReader in = new BufferedReader(new InputStreamReader( 
  55.                     client.getInputStream())); 
  56.             PrintWriter out = new PrintWriter(client.getOutputStream()); 
  57.             out.println("Info from server: Connected to EP400Pro toolkit service"); 
  58.             out.println(availableCMD); 
  59.             out.println("--Info End--"); 
  60.             out.flush(); 
  61.             // Mutil User but can't parallel 
  62.             while (true) { 
  63.                 String str = in.readLine(); 
  64.                 logger.info(str); 
  65.                 if (str.toLowerCase().equals("start")) { 
  66.                     workCommand(out, "net start " + service); 
  67.                     out.println("--Info End--"); 
  68.                     out.flush(); 
  69.                 } 
  70.                 else if (str.toLowerCase().equals("stop")) { 
  71.                     workCommand(out, "net stop " + service); 
  72.                     out.println("--Info End--"); 
  73.                     out.flush(); 
  74.                 } 
  75.                 else if (str.toLowerCase().equals("restart")) { 
  76.                     if (workCommand(out, "net stop " + service)) { 
  77.                         workCommand(out, "net start " + service); 
  78.                     } 
  79.                     out.println("--Info End--"); 
  80.                     out.flush(); 
  81.                 } 
  82.                 else if (str.toLowerCase().equals("exit")) { 
  83.                     break
  84.                 } 
  85.                 else if (str.toLowerCase().equals("clsv")) { 
  86.                     closeServer = true
  87.                     out.println("Info from server: EP400Pro toolkit service is to be closed"); 
  88.                     logger.info("EP400Pro toolkit service is to be closed"); 
  89.                     break
  90.                 } 
  91.                 else { 
  92.                     out.println("Info from server: Error commond\n" + availableCMD); 
  93.                     logger.info("Error commond\n" + availableCMD); 
  94.                     out.println("--Info End--"); 
  95.                     out.flush(); 
  96.                 } 
  97.             } 
  98.             out.println("Info from server: Disconnected to EP400Pro toolkit service"); 
  99.             out.println("--Info End--"); 
  100.             out.flush(); 
  101.             client.close(); 
  102.             logger.info("Closed client: " + client.getInetAddress().getHostName() + "/" + 
  103.                     client.getInetAddress().getCanonicalHostName() + ":" + String.valueOf(client.getPort())); 
  104.             if (closeServer){ 
  105.                 logger.info("Close myself"); 
  106.                 System.exit(MAX_PRIORITY); 
  107.             } 
  108.         } catch (IOException e) { 
  109.             logger.error(e.getMessage()); 
  110.         } finally { 
  111.             if (!client.isClosed()){ 
  112.                 try { 
  113.                     client.close(); 
  114.                 } catch (IOException e) { 
  115.                     // TODO Auto-generated catch block 
  116.                     logger.error(e.getMessage()); 
  117.                 } 
  118.             } 
  119.         } 
  120.     } 
  121.      
  122.     private boolean workCommand(PrintWriter out, String cmd){ 
  123.         if (ExecuteCMD.invokeOuterApplication(cmd)) { 
  124.             out.println("Info from server: Execute \"" + cmd + "\" successfully"); 
  125.             logger.info("Execute \"" + cmd + "\" successfully"); 
  126.             return true
  127.         } 
  128.         else { 
  129.             out.println("Info from server: Execute \"" + cmd + "\" failed"); 
  130.             logger.error("Execute \"" + cmd + "\" failed"); 
  131.             return false
  132.         } 
  133.     } 

3, Client 批处理命令:

  
  
  
  
  1. :参数1: server 参数2: port 参数3: command 
  2. :command: 
  3. :start: 启动服务 
  4. :stop: 关闭服务 
  5. :restart:重启服务 
  6. :exit:退出本程序 
  7. :clsv:关闭EP400Pro Toolkit Service 
  8. :line:进入命令行模式 
  9. java -jar EP400ProToolkitClient.jar 127.0.0.1 5678 line 
  10. pause 

4, Client类

  
  
  
  
  1. import java.io.BufferedReader; 
  2. import java.io.InputStreamReader; 
  3. import java.io.PrintWriter; 
  4. //import java.net.InetAddress; 
  5. import java.net.Socket; 
  6.  
  7. import org.apache.log4j.Logger; 
  8. import org.apache.log4j.PropertyConfigurator; 
  9.  
  10. public class RestartClient { 
  11.     private static Logger logger = Logger.getLogger(RestartClient.class.getName()); 
  12.     static Socket server; 
  13.  
  14.     public static void main(String[] args) throws Exception { 
  15.         String serverStr = null
  16.         String para = null
  17.         int port = 0
  18.         PropertyConfigurator.configure("log4j.properties"); 
  19.         if (args.length == 3){ 
  20.             logger.info("Server " + args[0]); 
  21.             logger.info("Server port " + args[1]); 
  22.             logger.info("Command " + args[2]); 
  23.             serverStr = args[0].trim().toLowerCase(); 
  24.             if(args[1].matches("[0-9]+")){ 
  25.                 port = Integer.parseInt(args[1].trim()); 
  26.             } 
  27.             para = args[2].trim().toLowerCase(); 
  28.         } 
  29.         if (serverStr == null || serverStr.equals("") ||  
  30.                 para == null || para.equals("") ||  
  31.                 port < 1024 || port > 65535){ 
  32.             logger.warn("Please init parameters: server port (1024~65535) command"); 
  33.             System.exit(0); 
  34.         } 
  35.         //server = new Socket(InetAddress.getLocalHost(), 5678); 
  36.         server = new Socket(serverStr, port); 
  37.         BufferedReader in = new BufferedReader(new InputStreamReader( 
  38.                 server.getInputStream())); 
  39.         PrintWriter out = new PrintWriter(server.getOutputStream()); 
  40.         BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); 
  41.          
  42.         String serverResponse = in.readLine(); 
  43.         while (serverResponse != null){ 
  44. //Server端如果不发结束符,则一直等待在in.readline(); 我想也可以用线程来专门处理输入输出,但我没有试过。
  45.             if (serverResponse.equals("--Info End--")){ 
  46.                 break
  47.             } 
  48.             logger.info(serverResponse); 
  49.             serverResponse = in.readLine(); 
  50.         } 
  51.          
  52.         boolean byLine = para.equals("line"); 
  53.         String str = null
  54.         while (true) { 
  55.             str = (byLine ? wt.readLine() : (str == null ? args[2] : str)); 
  56.             out.println(str); 
  57.             out.flush(); 
  58.             logger.info("Commond \"" + str + "\" is sent to server"); 
  59.             serverResponse = in.readLine(); 
  60.             while (serverResponse != null){ 
  61.                 if (serverResponse.equals("--Info End--")){ 
  62.                     break
  63.                 } 
  64.                 logger.info(serverResponse); 
  65.                 serverResponse = in.readLine(); 
  66.             } 
  67.             if (str.toLowerCase().equals("exit") || str.toLowerCase().equals("clsv")) { 
  68.                 break
  69.             } 
  70.             if (!byLine){ 
  71.                 str = "exit"
  72.             } 
  73.         } 
  74.         logger.info("Exit successfully"); 
  75.         server.close(); 
  76.     } 

 

你可能感兴趣的:(java,socket)