第十四天 簡單聊天

生產者和消費者

package com.java.baidu;
public class Creater implements Runnable{
    private Product product;
    public Creater(Product product){
        this.product=product;
    }
    @Override
    public  void run() {
        while(true){
            synchronized(product){
                if(product.getNum()==0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("生產者生產一件產品");
                }
                product.setNum(1);
                try {
                    product.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package com.java.baidu;
public class Consumer implements Runnable{
    private Product product;
    public Consumer(Product product){
        this.product=product;
    }
    @Override
    public  void run() {
        while(true){
            synchronized(product){
                if(product.getNum()!=0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("消費了一件產品");
                }
                product.setNum(0);
                product.notify();
            }
        }
    }
}
package com.java.baidu;
public class Product {
    private int num=0;
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
}
package com.java.baidu;
public class Test {
    public static void main(String[] args) {
        Product product=new Product();
        Thread t1=new Thread(new Creater(product));
        Thread t2=new Thread(new Consumer(product));
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}

這裏寫圖片描述

基於TCP的服務端與客戶端

package com.java.test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.java.test.MyServerRead;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JList;

public class StartServer extends JFrame {
    private JPanel contentPane;
    private JTextArea textArea;
    private Socket socket;
    public boolean isRunning=true;
    private JButton button;
    public boolean isRunning() {
        return isRunning;
    }
    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StartServer frame = new StartServer();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public StartServer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("發送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton.setBounds(283, 189, 127, 52);
        contentPane.add(btnNewButton);

        textArea = new JTextArea();
        textArea.setBounds(10, 189, 250, 52);
        contentPane.add(textArea);
        button = new JButton("啓動服務器");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    ServerSocket server = new ServerSocket(8080);
                    System.out.println("服務器啓動");
                    socket = server.accept();
                    Thread t=new Thread(new MyServerRead(StartServer.this));
                    t.start();
                    System.out.println("有客戶端連接");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        button.setBounds(0, 10, 225, 69);
        contentPane.add(button);
    }
    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            System.out.println("服務器接收到的消息:"+line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void write(){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            String words=textArea.getText();
            System.out.println("服務器發送信息");
            bw.write("服務器說:  "+words+"\n");
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.java.test;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JList;

public class MyClient extends JFrame {
    private JPanel contentPane;
    private Socket socket;
    private JTextArea textArea;
    private JList list;
    DefaultListModel<String> model;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyClient frame = new MyClient();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("發送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                write();
            }
        });
        btnNewButton.setBounds(305, 200, 99, 36);
        contentPane.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("連接服務器");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {    
                try {
                    System.out.println("連接服務器");
                    socket =new Socket("192.168.0.85",8080);
                    System.out.println("服務器連接成功");
                    Thread t=new Thread(new MyClientRead(MyClient.this));
                    t.start();
                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }           
            }
        });
        btnNewButton_1.setBounds(264, 68, 160, 60);
        contentPane.add(btnNewButton_1);
        textArea = new JTextArea();
        textArea.setBounds(10, 207, 228, 45);
        contentPane.add(textArea);
        list = new JList();
        list.setBounds(10, 22, 228, 173);
        model=new DefaultListModel<>();
        list.setModel(model);
        contentPane.add(list);
    }
    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            model.addElement(line);
            System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void write(){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            String words=textArea.getText();
            bw.write(words+"\n");
            model.addElement("客戶端說:   "+words);
            textArea.setText("");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.java.test;
public class MyClientRead implements Runnable {
        private MyClient client;
        public MyClientRead(MyClient client){
            this.client=client;
        }
        @Override
        public void run() {
            while(true){
                client.read();
            }
        }
    }
package com.java.test;
public class MyServerRead implements Runnable{
    private StartServer startServer;
    public MyServerRead(StartServer startServer){
        this.startServer=startServer;
    } 
    @Override
    public void run() {
        while(startServer.isRunning){
            startServer.read();
        }
    }
}

這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章