今天发现一段有意思的程序,记录下来,娱乐自己.
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])); } }