java socket

来源:互联网 发布:js bind 用法 编辑:程序博客网 时间:2024/06/05 10:18


handler.java

对请求头处理

package com;import java.io.*;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;import java.nio.ByteBuffer;import java.nio.channels.*;import java.nio.charset.Charset;import java.util.HashMap;public class Handler implements Runnable {    Functions functions = new Functions();    MIME mime = new MIME();    HashMap<String, String> type = mime.getMime();    String contentType = null;    private Socket client = null;    public Handler(Socket client) {        this.client = client;    }    @Override    public void run() {        if (client!= null) try {            BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));            String header = reader.readLine();            System.out.println("客户端发送的请求信息:>>>>>>>>>>>>>");            System.out.println(header);            String resource = header.split(" ")[1];            System.out.println("客户端发送的请求信息结束:<<<<<<<<<<");            System.out.println("resource: " + resource);            System.out.println();            String suffix = null;            if (resource.equals("/")) {                resource = "/index.html";            }            String[] names = resource.split("\\.");            suffix = names[names.length - 1];            contentType = type.get(suffix);            ////////            String path = "/opt/" + resource;            File file = new File(path);            if (file.exists()) {                if (suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg")) {                    functions.readImg(file, client, contentType);                } else {                    functions.readFile(file, client, contentType);                }            } else {                PrintWriter out = new PrintWriter(client.getOutputStream(), true);                out.println("HTTP/1.0 404 NotFound");                out.println("Content-Type:text/html;charset=UTF-8");                out.println();                out.println("对不起,您寻求的资源在本服务器上不存在!");                out.close();                functions.closeSocket(client);            }        } catch (IOException e) {            System.out.println("HTTP服务器错误: " + e.getLocalizedMessage());        }    }    public static void main(String[] args) throws IOException {        int port = 8000;        ServerSocket serverSocket = new ServerSocket(port);        Socket client = null;        while (true) {            client = serverSocket.accept();            System.out.println(client + "链接到HTTP服务器");            Handler handler = new Handler(client);            new Thread(handler).start();        }    }}

function.java

package com;import java.io.*;import java.net.Socket;public class Functions {    public void closeSocket(Socket socket) {        try {            socket.close();            System.out.println(socket + "离开了HTTP服务器");            System.out.println();            System.out.println();        } catch (IOException e) {            e.printStackTrace();        }    }    public void readImg(File file,Socket client,String contentType){        PrintStream out = null;        FileInputStream fileInputStream = null;        try {            out = new PrintStream(client.getOutputStream(),true);            fileInputStream = new FileInputStream(file);            byte[] data = new byte[fileInputStream.available()];            out.println("HTTP/1.0 200 OK");            out.println("Content-Type:" + contentType + ";charset=UTF-8");            out.println("Content-Length:" + file.length());            out.println();            fileInputStream.read(data);            out.write(data);            fileInputStream.close();        } catch (IOException e) {            out.println("HTTP/1.0 500");            out.println();            out.flush();        }finally {            out.close();            closeSocket(client);        }    }    public void readFile(File file,Socket client,String contentType){        PrintWriter out = null;        try {            out = new PrintWriter(client.getOutputStream(),true);            FileReader reader = new FileReader(file);            BufferedReader bufferedReader = new BufferedReader(reader);            String string = null;            out.print("HTTP/1.0 200 OK");            out.print("Content-Type:" + contentType + ";charset=UTF-8");            out.println();            while ((string = bufferedReader.readLine()) != null){                out.println(string);            }        } catch (IOException e) {            out.print("HTTP/1.0 500");            out.println();            out.flush();        }finally {            out.close();            closeSocket(client);        }    }}

MIME.java

package com;import java.util.HashMap;public class MIME {    private HashMap<String,String> mime = new HashMap<>();    public MIME(){        mime.put("css","text/css");        mime.put("gif","image/gif");        mime.put("html","text/html;charset=utf-8");        mime.put("ico","image/x-icon");        mime.put("jpeg","image/jpeg");        mime.put("jpg","image/jpeg");        mime.put("js","text/javascript");        mime.put("json","application/json");        mime.put("pdf","application/pdf");        mime.put("png","image/png");        mime.put("svg","image/svg+xml");        mime.put("swf","application/x-shockwave-flash");        mime.put("tiff","image/tiff");        mime.put("txt","text/plain;charset=utf-8");        mime.put("wav","audio/x-wav");        mime.put("wma","audio/x-ms-wma");        mime.put("wmv","video/x-ms-wmv");        mime.put("xml","text/xml");    }    public HashMap<String, String> getMime() {        return mime;    }}

参考链接:
java Socket 实现多线程静态文件服务器

基于HTTP、NIO、单线程实现浏览器并发非阻塞访问服务器文件


原创粉丝点击