使用Socket通讯实现简单的Web服务器

package com.yusian.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
    public static void main(String[] args) {
        try {
            // 开启端口监听
            ServerSocket ss = new ServerSocket(8080);
            while (true) {
                // 等待客户端请求
                Socket socket = ss.accept();
                // 获取接收到的字节流并使用缓存字符流类换行读取
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(socket.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                // 读取请求信息的第一行获取文件名
                String path = br.readLine().split(" ")[1];
                path = path.substring(1);
                System.out.println(path);
                File file = new File(path);

                // 获取Socket的输出字节流,输入Http的响应头信息
                OutputStream os = socket.getOutputStream();
                os.write("HTTP/1.1 200 OK\r\n".getBytes());
                os.write("Content-Type:text/html\r\n".getBytes());
                os.write("\r\n".getBytes());
                // 如果请求的文件不存在则返回404,否则读取本地文件返回给客户端
                if (!file.exists()) {
                    os.write("404".getBytes());
                } else {
                    FileInputStream fis = new FileInputStream(file);
                    int length = 0;
                    byte[] buffer = new byte[1024];
                    while ((length = fis.read(buffer)) != -1) {
                        os.write(buffer, 0, length);
                    }
                }
                socket.shutdownOutput();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Leave a Reply