zoukankan      html  css  js  c++  java
  • 利用socket实现java程序自动关闭

    今天发现一段有意思的程序,记录下来,娱乐自己.

    1.实运行main方法时传两个参数   '应用命令'和'socket端口'

    步骤1.启动java程序,参数(start 80890),启动serverSocket,启动线程,

    步骤2.启动java程序,参数(shutdown 80890)启动socket客户端,推送字符串,服务端线程获取字符串,停止步骤2启动的程序,停止步骤1.启动的程序.

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    import com.boco.vip.framework.util.common.CollectionUtil;
    
    public class SocketUsing {
    	private static void controlServer(String appCommant,int port){
    		try{
    			Socket clientSock = new Socket("127.0.0.1",port);//创建socket客户端(客户端依赖服务端,服务端没有启动报异常)
    			if(appCommant.trim().toLowerCase().equals("shutdown")){//判断应用命令是否为shutdown
    				//创建输出流
    				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSock.getOutputStream()));
    				bw.write("shutdown/n");//向服务端传送"shutdown"
    				bw.flush();
    				bw.close();
    				clientSock.close();
    				System.exit(0);
    			}else{
    				System.exit(0);
    			}
    		}catch(Exception e){
    			if(appCommant.trim().toLowerCase().equals("shutdown")){
    				System.exit(0);
    			}else{
    				try{
    					final ServerSocket ss = new ServerSocket(port);
    					//匿名类,创建线程
    					new Thread(new Runnable(){
    						public void run(){
    							while(true){
    								try{
    									BufferedReader br = null;
    									try{
    										//创建输入流
    										br = new BufferedReader(new InputStreamReader(ss.accept().getInputStream()));
    										String command = br.readLine();
    										if(CollectionUtil.checkStringEmpty(command)&&"shutdown".equals(command)){
    											System.exit(0);
    										}
    									}catch(Exception eee){
    										
    									}
    								}catch(Exception e){
    									
    								}
    							}
    						}
    					}).start();
    				}catch(Exception ee){
    					
    				}
    			}
    			
    			
    			
    		}
    	}
    	
    	public static void main(String[] args){
    		controlServer(args[0],Integer.parseInt(args[1]));
    	}
    }
    

      

  • 相关阅读:
    字典树模板
    hdu 1013 Digital Roots(数论 模拟)
    linux shell输出带颜色文本
    homebrew update 出现Failure while executing: git pull --quiet origin refs/heads/master:refs/remotes/origin/master解决方案
    macosx 10.11 python pip install 出现错误OSError: [Errno 1] Operation not permitted:
    Leetcode Palindrome Linked List
    Leetcode Delete Node in a Linked List
    Leetcode Valid Anagram
    Leetcode Kth Smallest Element in a BST
    Leetcode Power of Two
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/2944756.html
Copyright © 2011-2022 走看看