Java学习笔记 - 第028天

每日要点

对象json化

第三方 - gson

例子1:将人转换为json格式
房屋类:

public class House {
    @Expose
    private double area;
    @Expose
    private double unitPrice;
    
    public House() {
    }
    
    public House(double area, double unitPrice) {
        this.area = area;
        this.unitPrice = unitPrice;
    }

    public double getArea() {
        return area;
    }

    public void setArea(double area) {
        this.area = area;
    }

    public double getUnitPrice() {
        return unitPrice;
    }

    public void setUnitPrice(double unitPrice) {
        this.unitPrice = unitPrice;
    }
}

人类:

public class Person {
    @Expose
    private String name;
    private int age;
    @Expose
    @SerializedName("housesArray")
    private List<House> houses;
    
    public Person() {
    }
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void buy(House house) {
        if (houses == null) {
            houses = new ArrayList<>();
        }
        houses.add(house);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<House> getHouses() {
        return houses;
    }

    public void setHouses(List<House> houses) {
        this.houses = houses;
    }
}

测试:

class Test01 {

    public static void main(String[] args) {
        Person person = new Person("王大锤", 18);
        person.buy(new House(52.5, 8000));
        person.buy(new House(120.8, 12000));
        // Gson gson = new Gson();
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String jsonStr =  gson.toJson(person);
        System.out.println(jsonStr);
    }
}
第三方 - fastgson
        String jsonStr = JSON.toJSONString(person);
        System.out.println(jsonStr);

TCP

创建服务器端步骤:

    1. 在指定的端口上创建服务器套接字
    1. 通过accept()方法监听客户端的连接
    • 该方法是一个阻塞方法如果没有客户端连接到服务器就一直保持阻塞状态
    1. 启动一个线程进行I/O操作(每个客户端在独立的线程中执行)

例子1:创建服务端

class ClientHandler implements Runnable {
    private Socket client;
    
    public ClientHandler(Socket client) {
        this.client = client;
    }
    
    @Override
    public void run() {
        try {
            InputStream in = client.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            OutputStream out = client.getOutputStream();
            PrintStream ps = new PrintStream(out);
            String tempStr;
            while ((tempStr = br.readLine()) != null) {
                if (tempStr.equals("bye")) {
                    client.close();
                    break;
                }
                ps.println(tempStr.toUpperCase());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Test02 {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        // 1. 在指定的端口上创建服务器套接字
        try (ServerSocket server = new ServerSocket(1234)) {
            System.out.println("服务器已经启动...");
            boolean isRunning = true;
            while (isRunning) {
                try {
                    // 2. 通过accept()方法监听客户端的连接
                    // 该方法是一个阻塞方法如果没有客户端连接到服务器就一直保持阻塞状态
                    Socket client = server.accept();
                    // 3. 启动一个线程进行I/O操作(每个客户端在独立的线程中执行)
                    service.execute(new ClientHandler(client));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

例子2:创建客户端

class Test03 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try (Socket client = new Socket("10.7.155.72", 1234)) {
            OutputStream out = client.getOutputStream();
            PrintStream ps = new PrintStream(out);
            InputStream in = client.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String str;
            while (! (str = scanner.nextLine()).equals("bye")) {
                ps.println(str);
                System.out.println(br.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        scanner.close();
    }
}

UDP

UDP - 用户数据报协议 - User Datagram Protocol
例子1:发送方

class Test04 {

    public static void main(String[] args) {
        try (DatagramSocket udpSocket = new DatagramSocket(6789)) {
            byte[] buf = "hello".getBytes();
            DatagramPacket p = new DatagramPacket(buf, buf.length,
                    InetAddress.getByName("10.7.155.72"), 3456);
            udpSocket.send(p);
            System.out.println("发送数据完成!");
        }
        catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

例子2:接收方

class Test05 {

    public static void main(String[] args) {
        try (DatagramSocket udpSocket = new DatagramSocket(3456)) {
            byte[] buf = new byte[1024];
            DatagramPacket p = new DatagramPacket(buf, buf.length);
            udpSocket.receive(p);
            String str = new String(buf, 0, p.getLength());
            System.out.println(str);
        }
        catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,818评论 11 349
  • 本文出自 Eddy Wiki ,转载请注明出处:http://eddy.wiki/interview-java.h...
    eddy_wiki阅读 2,299评论 0 14
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,647评论 19 139
  • 1、OC中创建线程的方法是什么?如果指定在主线程中执行代码?如何延时执行代码。【难度系数★★】 1)创建线程的方法...
    木旁_G阅读 2,087评论 2 16
  • 今天算是起了一个早头。印象中这样的次数不多,大多数发生在旅游的时候,起个大早赶火车,赶在人潮稀疏的时候。 其实很喜...
    彭小坚阅读 186评论 0 0

友情链接更多精彩内容