posts - 397,comments - 0,views - 25332

模拟BS服务器代码实现和函数式接口

代码实现:

复制代码
ServerSocket server = new ServerSocket(9090);
        while (true){
            Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is = socket.getInputStream();
//        byte[] bytes = new byte[1024];
//        int len = 0;
//        while ((len=is.read(bytes))!=-1){
//            System.out.println(new String(bytes,0,len));
//        }
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        String s = br.readLine();
                        System.out.println(s);
                        String[] s1 = s.split(" ");
                        String substring;
                        if (s1[1].equals("/favicon.ico")){
                            substring = "src/web/index.html";
                        }else {
                            substring  = s1[1].substring(9);
                        }
                        FileInputStream fileInputStream = new FileInputStream(substring);
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                        outputStream.write("Content-Type:text/html\r\n".getBytes());
                        outputStream.write("\r\n".getBytes());
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len=fileInputStream.read(bytes))!=-1){
                            outputStream.write(bytes,0,len);
                        }
                        fileInputStream.close();
                        socket.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
复制代码

打印

 

 

 

 

 

函数式接口的的定义

概念:

 

函数式接口在java中是指:有且仅有一个抽象方法的接口

函数式接口,计适用于函数式编程的场景的接口,而Java中的函数式编程题体现就是lambda,所以函数式接口就是可以适用于

Lambda使用的接口只有确保接口中且有一个抽象方法,java中的Lambda才能顺利的进行推到

备注:

  语法糖:是指使用更加方便,但是原理不变的代码语法,例如在遍历集合时使用for-each语法,

  其实底层的原理任然是迭代器,这便是语法糖,从应用层来讲,java中的Lambda可以被当做匿名内部类

  “语法糖”,但是二者在原理是不同的。

格式:

修饰符 interface 接口名{
  public abstract 返回值类型 方法名称(可选参数信息);
  //其他非抽象方法内容 }

由于接口中的抽象方法的 public abstract 是可以神略的,所以定一个函数式接口

public interface MyFunctionInterface {
  void myMethod(); }
当然接口中可以包括其他方法(默认,静态,私有)
@FunctionalInterface
作用:可以检测接口是否是一个函数式接口
是:编译成功
否:编译失败

 

 

posted on   淤泥不染  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示