美文网首页
Java学习笔记 - 第028天

Java学习笔记 - 第028天

作者: 迷茫o | 来源:发表于2017-01-07 10:24 被阅读0次

    每日要点

    对象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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Java学习笔记 - 第028天

          本文链接:https://www.haomeiwen.com/subject/gaffbttx.html