1,服务端 public class Server { public static void main(String[] args) { try { final ServerSocket server = new ServerSocket(10000); ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); cachedThreadPool.execute(new Runnable() { @Override public void run() { while (true) { try { Long start=System.currentTimeMillis(); System.out.println("start..."); Socket socket = server.accept(); System.out.println("连接耗时:t="+(System.currentTimeMillis()-start)); cachedThreadPool.execute(new Runnable() { @Override public void run() { String tmpName=receiveImg(socket); Long end=System.currentTimeMillis(); System.out.println(new Date()+",tmpName="+tmpName+",耗时:t="+(end-start)); } }); } catch (Exception e) { e.printStackTrace(); } } } }); } catch (Exception e) { e.printStackTrace(); } }
public static String receiveImg(Socket socket) { byte[] inputByte = null; Integer length = 0; DataInputStream dis = null; FileOutputStream fos = null; OutputStream out =null; String tmpName="image/"+ UUID.randomUUID()+".jpg"; try { System.out.println("start receive..."); InputStream inputStream=socket.getInputStream(); dis = new DataInputStream(inputStream); fos = new FileOutputStream(new File(tmpName)); inputByte = new byte[1]; while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) { String str=new String(inputByte,0,length); if (str.equals("6")){ break; } } System.out.println("img receive end"); //获取输出流,准备给客户端发送消息 out = socket.getOutputStream(); out.write("success".getBytes()); } catch (Exception e) { e.printStackTrace(); } return tmpName; } }
2,客户端
public class Client { public static void main(String[] args) { int length = 0; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; try { try { //123.57.63.199 for (int i=0;i<2;i++){ Long start=System.currentTimeMillis(); socket = new Socket(); socket.connect(new InetSocketAddress("127.0.0.1", 10000), 10 * 1000); System.out.println("start..."); dos = new DataOutputStream(socket.getOutputStream()); Long end=System.currentTimeMillis(); System.out.println(new Date()+",耗时:t="+(end-start)); File file = new File("D:\\我的文档\\Pictures\\3.jpg"); fis = new FileInputStream(file); sendBytes = new byte[1024]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { dos.write(sendBytes, 0, length); } dos.write("\r\n".getBytes()); dos.flush(); //通知服务端,数据发送完毕 socket.shutdownOutput(); //3.获取输出流,接受服务器传送过来的消息 InputStream in = socket.getInputStream(); byte[] bufIn = new byte[1024]; int num = in.read(bufIn); String readStr=new String(bufIn,0,num); System.out.println(readStr); } } } catch (Exception e) { e.printStackTrace(); } } }