package com.bbs2018.server; import java.io.*; import java.net.ServerSocket; import java.net.Socket; //https://blog.csdn.net/zqq3436/article/details/80306812 public class Server { public static void main(String[] args) { ServerSocket server = null; Socket socket = null; String basePath = "E:\\webapps"; try { server = new ServerSocket(8080); System.out.println("服务器已启动...."); while(true) { socket = server.accept(); //System.out.println("123"); service(socket.getInputStream(), socket.getOutputStream(), basePath); } } catch(IOException e) { e.printStackTrace(); } } private static void service(InputStream in, OutputStream out, String basePath) throws IOException { //读取本地index.html文件的流对象 BufferedReader br = null; try { //1、接收并解析客户端发来的请求信息 int len = in.available(); //System.out.println(len); byte[] buffer = new byte[len]; in.read(buffer);//以上三行,得到客户端的请求信息 String request = new String(buffer); //2、得到客户端想要的文件路径,从本地系统,读取该文件 File reqFile = new File(basePath, request); //判断请求文件是否存在。 /*if (!reqFile.exists()) { //System.out.println("该文件不存在!"); return; }*/ //3、将读取的信息。发送给客户端 br = new BufferedReader(new FileReader(reqFile)); //边读取index.html文件,边向客户端发送 String line = null; while((line = br.readLine()) != null) { out.write((line + "\r\n").getBytes()); } } catch(FileNotFoundException e) { out.write("404".getBytes()); out.flush(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } if (br != null) { br.close(); } } } }
2、Client端
package com.bbs2018.client; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; //https://blog.csdn.net/zqq3436/article/details/80306812 public class Client { public static void main(String[] args) { Socket client = null; try { //1、连接服务器 client = new Socket("127.0.0.1", 8080); //2、向服务器发送请求信息 OutputStream out = client.getOutputStream(); out.write("\\hello\\index.html".getBytes()); out.flush();//刷新给服务器端文件路径 Thread.sleep(1000);//此处休眠很重要 //3、接收服务器发送的信息,并打印输出到控制台 InputStream in = client.getInputStream(); //int len = in.available(); byte[] buffer = new byte[1024]; int len = -1; while((len = in.read(buffer)) != -1) { System.out.println(new String(buffer, 0, len)); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (client != null) { try { client.close(); } catch(IOException e) { e.printStackTrace(); } } } } }