1 SocketClient.java 代码
package com.cpcnet.socket; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.cpcnet.util.MyLogger; import com.cpcnet.util.PropertiesUtil; import com.cpcnet.util.StringUtil; public class SocketClient { private MyLogger logger = new MyLogger(SocketClient.class); public static String CMD=PropertiesUtil.getProp("socket.properties", "CMD"); private Socket socket = null; private BufferedReader br = null; private PrintWriter pw = null; public String getTheFiles(String cmd,List<String> gidList){ this.logger.info("SocketClient.java getTheFiles(String cmd,List<String> gidList) cmd = " + cmd + " gidList = " + gidList); boolean flag = true; String result = null; String ip = PropertiesUtil.getProp("socket.properties", "ip"); int port = Integer.parseInt(PropertiesUtil.getProp("socket.properties", "port")); if(!this.connect(ip, port)){ this.logger.error("SocketClient.java connect falied"); flag = false; }else{ this.logger.info("SocketClient.java connect success"); this.logger.info("SocketClient.java connect Socket = " + socket); System.out.println("Socket=" + socket); try { br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()))); } catch (IOException e) { flag = false; this.logger.error("SocketClient.java br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()))); "); e.printStackTrace(); } if(!this.sendCmd(cmd, gidList)){ flag = false; this.logger.error("SocketClient.java sendCmd(cmd, gidList) failed "); } if(flag){ result = this.getMessage(); System.out.println("SocketClient.java result = " + result); } } this.close(); return result; } public String getMessage(){ String result = null; String str = null; try { str = br.readLine(); System.out.println("server message = "+str); result = str; Thread.sleep(1); } catch (Exception e) { this.logger.error("SocketClient.java getMessage() error"); e.printStackTrace(); } pw.flush(); return result; } public boolean sendCmd(String cmd,List<String> gidList){ boolean flag = true; if(CMD.equals(cmd)&&gidList.size() > 0){ String gidListString = StringUtil.ListToString(gidList); // String gidListString = StringUtil.gidStringConvertList(gidStr) String sendCmd = cmd + "and" + gidListString ; pw.println(sendCmd); pw.flush(); }else{ this.logger.error("SocketClient.java sendCmd(String cmd,List<String> gidList) cmd = " + cmd + " gidList = " + gidList); flag = false; } return flag; } public boolean connect(String ip ,int port){ boolean flag = true; try { socket = new Socket(ip, port); } catch (IOException e) { flag = false; e.printStackTrace(); } return flag; } public void close(){ try { br.close(); pw.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block this.logger.error("SocketClient.java close() error"); e.printStackTrace(); } } public static void main(String[] args) { String cmd = PropertiesUtil.getProp("socket.properties", "CMD"); // List<String> gidList = new ArrayList<String>(); // gidList.add("20186"); // gidList.add("40435"); // gidList.add("40699"); // new SocketClient().getTheFiles(cmd, gidList); // // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // List<String> gidList2 = new ArrayList<String>(); gidList2.add("19934"); gidList2.add("40435"); gidList2.add("40699"); new SocketClient().getTheFiles(cmd, gidList2); // {20186=[all_sites_traffic_summary_201502.html, all_sites_traffic_summary_201503.html], 40435=[], 40699=[]} } }
2 SocketServer.java 代码
package com.cpcnet.socket; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cpcnet.util.ListUtil; import com.cpcnet.util.MyLogger; import com.cpcnet.util.PropertiesUtil; public class SocketServer { private ServerSocket serverSocket = null; private Socket socket = null; private BufferedReader br = null; private PrintWriter pw = null; private MyLogger logger = new MyLogger(SocketServer.class); private String CMD=PropertiesUtil.getProp("socket.properties", "CMD"); private String cmd = null; private String gidListString = null; private String error = PropertiesUtil.getProp("socket.properties", "error"); public boolean init(){ boolean flag = true; int port = Integer.parseInt(PropertiesUtil.getProp("socket.properties", "port")); //设定服务端的端口号 try { serverSocket = new ServerSocket(port); } catch (IOException e) { this.logger.error("SocketServer.java serverSocket = new ServerSocket(PORT); port = " + port); flag = false; e.printStackTrace(); } System.out.println("ServerSocket Start:"+serverSocket); return flag; } public boolean start(){ boolean flag = true; if(!this.init()){ this.logger.error("SocketServer.java init() failed "); }else{ while(true){ try { socket = serverSocket.accept(); System.out.println("Connection accept socket:" + socket); Thread thread = this.initThread(socket, logger); thread.start(); // thread.stop(); } catch (IOException e) { this.logger.error("SocketServer.java start() init the br and pw error"); try { socket.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); return false; } } } return flag; } public Thread initThread( final Socket socket, final MyLogger logger){ Thread thread = new Thread(new Runnable(){ public void run(){ try { //用于接收客户端发来的请求 br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //用于发送返回信息,可以不需要装饰这么多io流使用缓冲流时发送数据要注意调用.flush()方法 pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // while(true){ if(!this.getMessage()){ logger.error("SocketServer.java getMessage() failed " ); } if(!this.sendMessage()){ logger.error("SocketServer.java sendMessage() failed"); } try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("close socket and socket = " + socket); // this.close(); // } } public void close(){ try { br.close(); pw.close(); socket.close(); // serverSocket.close(); } catch (IOException e) { logger.error("SocketServer.java close() error"); e.printStackTrace(); } } public boolean getMessage(){ boolean flag = true; String cmdAndGidListAndMonth = null; try { cmdAndGidListAndMonth = br.readLine(); } catch (IOException e) { logger.error("SocketServer.java getMessage() error"); e.printStackTrace(); return false; } if(cmdAndGidListAndMonth != null){ System.out.println("SocketServer.java cmdAndGidListAndMonth = " + cmdAndGidListAndMonth); cmd = cmdAndGidListAndMonth.split("and")[0]; gidListString = cmdAndGidListAndMonth.split("and")[1]; } return flag; } public boolean sendMessage(){ boolean flag = true; if (CMD.equals(cmd)) { String fileBasicPath = PropertiesUtil.getProp("socket.properties", "fileBasicPath"); Map<String,List<String>> map_gid_list = new HashMap<String,List<String>>(); List gidList = ListUtil.StringToList(gidListString); if(gidList!= null && gidList.size() > 0){ for(int i = 0 ; i < gidList.size() ; i ++ ){ String filePath = fileBasicPath + gidList.get(i); List<String> gid_list = this.getFilesByGid(filePath); map_gid_list.put((String) gidList.get(i), gid_list); } System.out.println("map_gid_list.toString() = " + map_gid_list.toString()); pw.println(map_gid_list.toString()); pw.flush(); }else{ flag =false; logger.error("SocketServer.java sendMessage error : this.cmd = " + cmd + " this.gidList = " + gidList ); } } return flag; } public List<String> getFilesByGid(String filePath){ List<String> list = new ArrayList<String>(); File sumamryGidFile = new File(filePath); if(!sumamryGidFile.exists()) sumamryGidFile.mkdir(); File[] childFiles = sumamryGidFile.listFiles(); if(childFiles != null &&childFiles.length > 0){ for(int j = 0 ; j < childFiles.length ; j ++){ if(!childFiles[j].isDirectory()){ String childFileName = childFiles[j].getName(); childFileName = childFileName.split("\\.")[0]; childFileName = childFileName.split("_")[4]; list.add(childFileName); } } } return list; } }); return thread; } public static void main(String[] agrs) { boolean flag = new SocketServer().start(); } }