day17

聊天多对多

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
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.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

import net.sf.json.JSONObject;

public class MyServer extends JFrame {

    private JPanel contentPane;
    private HashMap<String, Socket> sockets;
    private boolean isRunning = true;
    private JTextArea textArea;
    private DefaultListModel<String> modle;

    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 {
                    MyServer frame = new MyServer();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

        JButton button = new JButton("服务器开启");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("服务器已经开启");

                Runnable run=new Runnable() {

                    @Override
                    public void run() {
                        try {
                            ServerSocket server = new ServerSocket(8080);
                            sockets=new HashMap<>();
                            while (true) {
                                Socket socket = server.accept();
                                System.out.println("连接上客户端:"+socket.getInetAddress().getHostAddress());
                                String ip=socket.getInetAddress().getHostAddress();
                                sockets.put(ip, socket);
                                MyServerRead msr=new MyServerRead(socket,MyServer.this);
                                Thread thread=new Thread(msr);
                                thread.start();
                            }
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                };
                Thread t=new Thread(run);
                t.start();

            }
        });
        button.setBounds(695, 104, 140, 174);
        contentPane.add(button);

        textArea = new JTextArea();
        textArea.setBounds(22, 476, 663, 138);
        contentPane.add(textArea);

        JButton button_1 = new JButton("发送");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                modle.addElement(textArea.getText());
            }
        });
        button_1.setBounds(695, 476, 140, 138);
        contentPane.add(button_1);
        modle = new DefaultListModel<>();
        JList list = new JList();
        list.setModel(modle);
        list.setBounds(22, 10, 663, 460);
        contentPane.add(list);
    }
    public void readLine(String line){
        JSONObject obj=JSONObject.fromObject(line);
        String type=obj.getString("type");
        System.out.println("收到:"+line);
        if(type.equals("toSingle")){
            String msg=obj.getString("message");
            String to=obj.getString("to");
            String from=obj.getString("from");
            String time=obj.getString("time");
            Socket toSocket=sockets.get(to);
            System.out.println(toSocket.getInetAddress().getHostAddress());
            try {
                OutputStream os=toSocket.getOutputStream();
                BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
                bw.write(msg+"\n");
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        modle.addElement(line);
    }

    public void write(String msg) {
        try {
            Set<String> keys = sockets.keySet();
            Iterator<String> it = keys.iterator();
            while (it.hasNext()) {
                Socket socket = sockets.get(it.next());
                OutputStream os = socket.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                bw.write(msg + "\n");
                bw.flush();
            }
            textArea.setText("");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
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.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.DefaultMenuLayout;

import net.sf.json.JSONObject;
import javax.swing.JTextField;
import javax.swing.JLabel;

public class MyClient extends JFrame {

    private JPanel contentPane;
    private Socket socket;
    private JTextArea textArea;
    private JList list;
    private DefaultListModel<String> modle;
    private JTextField textField;

    /**
     * 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, 819, 598);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textArea = new JTextArea();
        textArea.setBounds(49, 436, 500, 101);
        contentPane.add(textArea);

        JButton btnNewButton = new JButton("发送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String msg=createMessage();
                write(msg);
            }
        });
        btnNewButton.setBounds(570, 436, 154, 101);
        contentPane.add(btnNewButton);

        list = new JList();
        list.setBounds(49, 10, 500, 416);
        modle = new DefaultListModel<>();
        list.setModel(modle);
        contentPane.add(list);

        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.84", 8080);
                    System.out.println("连接完成");
                    Thread t = new Thread(new MyClientRead(MyClient.this));
                    t.start();
                } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton_1.setBounds(555, 68, 208, 86);
        contentPane.add(btnNewButton_1);

        textField = new JTextField();
        textField.setBounds(570, 319, 173, 47);
        contentPane.add(textField);
        textField.setColumns(10);

        JLabel lblip = new JLabel("请输入你想要连接的IP地址");
        lblip.setBounds(570, 271, 199, 47);
        contentPane.add(lblip);
    }

    public void read() {
        try {

            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            modle.addElement("" + line);
            System.out.println("收到:"+line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String createMessage(){
        String msg = textArea.getText();
        JSONObject obj = new JSONObject();
        obj.put("message", msg);
        obj.put("type", "toSingle");
        Calendar calendar = Calendar.getInstance();
        long time = calendar.getTimeInMillis();
        obj.put("time", "" + time);
        obj.put("from", socket.getInetAddress().getHostAddress());
        obj.put("to", textField.getText());
        System.out.println(obj.toString());
        return obj.toString();
    }
    public void write(String msg) {
        try {
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os);
            BufferedWriter bw=new BufferedWriter(osw);
            bw.write(msg+"\n");
            bw.flush();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
public class MyClientRead implements Runnable{
    private MyClient client;
    public MyClientRead(MyClient  client){
        this.client=client;
    }
    @Override
    public void run() {
        while(true){
            client.read();
        }
    }

}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class MyServerRead implements Runnable {
    private Socket socket;
    private MyServer server;
    public MyServerRead(Socket socket,MyServer server) {
        this.socket=socket;
        this.server=server;
    }

    @Override
    public void run() {
        try {
            InputStream is=socket.getInputStream();
            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(isr);
            while(true){
                String line=br.readLine();
                server.readLine(line);
                System.out.println("收到:"+line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值