模拟web服务器,处理http协议;java手写实现;端口监听; ServerSocket

/**
 * 模拟web服务器,能处理http协议
 * 1: http协议的定义  content-type
 *     4个字节  0001 男,0000 女
 * 2: 网络编程
 *      客户端,服务器端
 *
 *
 * 场景:假装一个web服务器
 *    bio编程,blocking
 */
/**
 * 模拟web服务器,能处理http协议
 * 1: http协议的定义  content-type
 *     4个字节  0001 男,0000 女
 * 2: 网络编程
 *      客户端,服务器端
 *
 *
 * 场景:假装一个web服务器
 *    bio编程,blocking
 */
public class Test {
    public static void main(String[] args) throws Exception {
        ServerSocket service=new ServerSocket();
        InetSocketAddress port = new InetSocketAddress(8848);
        service.bind(port);
        Socket accept = service.accept();
        InputStream is = accept.getInputStream();
        OutputStream os = accept.getOutputStream();
        byte[]bytes=new byte[1024];
        int read = is.read(bytes);
        String s = new String(bytes, 0, read);
        System.out.println(cutString(s, "/", "HTTP"));
//        String[] split = s.split("/.*HTTP");
//        for (String s1 : split) {
//            System.out.print(s1);
//        }
//        File file = new File("246859564411688080.jpg");
//
//        BufferedReader fileReader = new BufferedReader(new FileReader(file));
        //if
        String s6="WANGYU666";
        Integer status=200;
        String ok="OK";
        String copy="HTTP/1.1";
        String contentType="Content-Type: text/html; charset=utf-8";
        //String contentType="Content-Type: image/jpeg";
        //image
        //String s1 = fileReader.readLine();
        String text="WANGYU666";
        String s1="C:Users\\Lara\\Desktop\\中国地图.jpg";
        //String context="<img"+"src="+"\""+s1+"\""+">";
        String context="<h1>"+text+"</h1>";
        String all=copy+" "+status+" "+ok+"\r\n"+contentType+"\r\n"+"\r\n"
               +context;
        os.write(all.getBytes());
        //os.write(s.getBytes());
        os.flush();
    }
    public static String cutString(String str, String start, String end) {
        if (str.isBlank()) {
            return str;
        }
        String reg= start + "(.*)" + end;//  "/.*HTTP"
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            str = matcher.group(1);
        }
        return str;
    }
    /**
     * 1.如果字符串中含有多个#或多个$,使用以第一个#为起始或以最后一个$为结束。
     *
     * 2.'$'或'.'等特殊字符要转义
     */
}

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值