1说明
监听某端口,当浏览器请求过来时,返回网页信息
2显示效果
3代码
package _1; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.OutputStream; public class wewe { /** * 启动监听 * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { new wewe().demo(); } private void demo() throws IOException { String path = getClass().getClassLoader().getResource("").getPath(); ServerSocket serverSocket = new ServerSocket(666); System.out.println("Server is starting " + serverSocket); Socket socket = null; while (true) { socket = serverSocket.accept(); InputStream is = socket.getInputStream(); String configs = inputStream2String(is); dealConfigs(configs, path, socket); } } /** * 获取输入 * * @param in * @return * @throws IOException */ public String inputStream2String(InputStream in) throws IOException { StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; in.read(b); out.append(new String(b)); return out.toString(); } /** * 处理页面响应 * * @param configs * @throws IOException */ public void dealConfigs(String _configs, String path, Socket socket) throws IOException { String[] configs = _configs.split("\r\n"); Map<String, String> request = new HashMap<>(); for (String config : configs) { if ("".equals(config.trim())) { continue; } if (config.contains(":")) { String[] temp = config.split(":"); request.put(temp[0], temp[1]); } else { String[] temp = config.split(" "); request.put("METHOD", temp[0]); request.put("URL", temp[1]); request.put("HTTP", temp[2]); } } System.out.println(request); if (request.containsKey("URL")) { String filepath = path.substring(1, path.length() - 1) + request.get("URL"); byte[] file = getBytes(filepath); output(file, socket); } } /** * 把文件转成byte[] * * @author wangw40 * @date 2015年12月14日 下午6:15:06 * @explain * @param filePath * @return */ private static byte[] getBytes(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } public void output(byte[] buff2, Socket socket) throws IOException { // response.addHeader("Content-Length", buff2.length + ""); // 设置下载文件大小 // response.setContentType("image/png"); // 获取输出流 OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(socket.getOutputStream()); outputStream.write(buff2, 0, buff2.length); } finally { if (outputStream != null) { outputStream.close(); } } } }