简单的聊天系统

来源:互联网 发布:玄武吉他淘宝店链接 编辑:程序博客网 时间:2024/05/02 00:09

界面:

package com.lovo.socketgui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class FlySpringFrame extends JFrame {
    private static Properties props;

    private Container contentP;

    private JScrollPane scorollP;

    private JTextArea msgAre;

    private JTextField inputTxt;

    private JButton sendBtn;

    private JComboBox ipCom;

    private JButton clearBtn;

    private JCheckBox autoBackChoice;

    private JTextField autoBackTxt;

    private ServerSocket ss;

    static {
        props = new Properties();
        try {
            props.load(new FileInputStream("name1.properties"));

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public FlySpringFrame() {
        Toolkit tk = Toolkit.getDefaultToolkit();
        this.setTitle("我的飞春");
        // 设置窗体位置
        this.setLocation(((int) tk.getScreenSize().getWidth() - 500) / 2,
                ((int) tk.getScreenSize().getHeight() - 400) / 2);
        // 设置窗体大小
        this.setSize(500, 400);
        // 设置窗体大小不可变
        this.setResizable(false);
        // 设置关闭
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addContent();
        this.setVisible(true);

        // 服务器监听
        try {
            ss = new ServerSocket(9527);
            while (true) {
                Socket socket = ss.accept();
                new ProcessThread(socket, this.msgAre, this.autoBackChoice,
                        this.autoBackTxt).start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private void addContent() {
        // TODO Auto-generated method stub
        this.contentP = this.getContentPane();
        this.contentP.setBackground(Color.WHITE);
        this.contentP.setLayout(null);

        this.msgAre = new JTextArea();
        this.scorollP = new JScrollPane(this.msgAre);
        this.scorollP.setBounds(20, 20, 460, 250);
        this.contentP.add(this.scorollP);
        this.msgAre.setEditable(false);

        this.inputTxt = new JTextField();
        this.inputTxt.setBounds(20, 300, 200, 30);
        this.contentP.add(this.inputTxt);

        this.sendBtn = new JButton("发送");
        this.sendBtn.setBounds(240, 300, 60, 30);
        this.contentP.add(this.sendBtn);

        this.sendBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                String input = inputTxt.getText();
                inputTxt.setText("");
                if (input == null || input.trim().equals("")) {
                    JOptionPane.showMessageDialog(contentP, "不能发送空消息");
                } else {
                    input = "胡老师&" + input;
                    Socket sendSocket = null;
                    try {

                        String name = ipCom.getSelectedItem().toString();
                        String ip = props.getProperty(name);
                        if (ip == null || ip.equals("")) {
                            ip = name;
                            
                        }

                        if (!ip.matches("(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])")) {
                            input = "友情提示&请输入有效的IP地址或在好友列表中选择好友";
                            ipCom.setSelectedIndex(0);
                        } else {
                            sendSocket = new Socket(ip, 9527);
                            BufferedWriter bw = new BufferedWriter(
                                    new OutputStreamWriter(sendSocket
                                            .getOutputStream()));
                            bw.write(input);
                            bw.flush();
                        }
                        msgAre.append(input.split("&")[0] + "说:"
                                + input.split("&")[1] + "\n");
                    } catch (UnknownHostException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } finally {
                        if (sendSocket != null) {
                            try {
                                sendSocket.close();
                            } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                        }

                    }
                }
            }
        });

        Set allKey = props.keySet();
        Object[] allNames = allKey.toArray();
        this.ipCom = new JComboBox(allNames);
        this.ipCom.setBounds(320, 300, 100, 30);
        this.ipCom.setEditable(true);
        this.contentP.add(this.ipCom);

        this.clearBtn = new JButton("清屏");
        this.clearBtn.setBounds(430, 300, 60, 30);
        this.contentP.add(this.clearBtn);
        this.clearBtn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                msgAre.setText("");
            }

        });

        this.autoBackChoice = new JCheckBox("自动回复");
        this.autoBackChoice.setBounds(20, 340, 80, 30);
        this.autoBackChoice.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (autoBackChoice.isSelected()) {
                    autoBackTxt.setEditable(true);
                } else {
                    autoBackTxt.setEditable(false);
                }
            }

        });
        this.contentP.add(this.autoBackChoice);

        this.autoBackTxt = new JTextField("我不在,请稍后联系");
        this.autoBackTxt.setBounds(120, 340, 200, 30);
        this.autoBackTxt.setEditable(false);
        this.contentP.add(this.autoBackTxt);
    }

}


线程:

package com.lovo.socketgui;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JCheckBox;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ProcessThread extends Thread {
    private Socket socket;

    private JTextArea msgArea;

    private JCheckBox autoBackChoice;

    private JTextField autoBackTxt;

    public ProcessThread(Socket socket, JTextArea msgArea,JCheckBox autoBackChoice,JTextField autoBackTxt) {
        this.socket = socket;
        this.msgArea = msgArea;
        this.autoBackChoice = autoBackChoice;
        this.autoBackTxt = autoBackTxt;
    }

    public void run() {
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            String msg = br.readLine();
            String[] allMsg = msg.split("&");
            msgArea.append(allMsg[0] + "("
                    + socket.getInetAddress().getHostAddress() + "):"
                    + allMsg[1] + "\n");
            msgArea.setCaretPosition(msgArea.getText().length());// 自动跳到最后位置
            // 自动回复
            if(this.autoBackChoice.isSelected()){
                this.autoReturn();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void autoReturn() {
//        int num = (int) (Math.random() * 3) + 1;
//        String backMsg = "";
//        switch (num) {
//        case 1:
//            backMsg = "胡老师&你好,我正在忙,请稍后再联系!";
//            break;
//        case 2:
//            backMsg = "胡老师&真的是你吗?";
//            break;
//        case 3:
//            backMsg = "胡老师&好的,我知道了!";
//        }
        String backMsg = this.autoBackTxt.getText();
        if(backMsg.trim().equals("")){
            backMsg = "我不在,请稍后联系";
        }
        backMsg = "胡老师&" + backMsg;
        String address = this.socket.getInetAddress().getHostAddress();
        if (!address.equals("127.0.0.1")) {
            Socket sendSocket = null;
            try {
                sendSocket = new Socket(address, 9527);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                        sendSocket.getOutputStream()));
                bw.write(backMsg);
                bw.flush();
            } catch (UnknownHostException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    sendSocket.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
}


测试:

package com.lovo.test;

import com.lovo.socketgui.FlySpringFrame;

public class TestMain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        new FlySpringFrame();
        
        
//        String regex = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))";
//        String ip = JOptionPane.showInputDialog("");
//        if(ip.matches(regex)){
//            JOptionPane.showMessageDialog(null, "Success");
//        }else{
//            JOptionPane.showMessageDialog(null, "Failed");
//        }
    }
}




0 0
原创粉丝点击