码迷,mamicode.com
首页 > 其他好文 > 详细

聊天室客户端实现

时间:2017-11-21 23:50:49      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:line   input   cal   extend   stream   ase   trace   final   pre   

登入界面

public class LoginFrame extends JFrame implements ActionListener{

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoginFrame frame = new LoginFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LoginFrame() {
        try {
            UIManager.setLookAndFeel(new SeaGlassLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        
        textField = new JTextField();
        textField.setColumns(10);
        
        JButton button = new JButton("登入");
        button.addActionListener(this);
        
        JLabel label = new JLabel("\u7528 \u6237 \u540D");
        
        textField_1 = new JTextField();
        textField_1.setColumns(10);
        
        JLabel lblip = new JLabel("\u670D\u52A1\u5668IP");
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(180)
                            .addComponent(button))
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(38)
                            .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                                .addComponent(label)
                                .addComponent(lblip))
                            .addGap(18)
                            .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
                                .addComponent(textField_1)
                                .addComponent(textField, GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))))
                    .addContainerGap(129, Short.MAX_VALUE))
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGap(94)
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(label))
                    .addGap(18)
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                        .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblip))
                    .addPreferredGap(ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                    .addComponent(button)
                    .addGap(50))
        );
        contentPane.setLayout(gl_contentPane);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        
        JButton button = (JButton) e.getSource();
        if(button.getText().equals("登入")){
            String sendMsg ="1000"+"|"+textField.getText();
            try {
                Socket s = MyClient.connect(textField_1.getText().trim(), 8080);
                String responseMsg = LoginListener.login(s, sendMsg);
                String[] datas = responseMsg.split("\\|");
                if(datas[0].equals("0000")){
                    String[] users = new String[datas.length-1];
                    for (int i = 0; i < users.length; i++) {
                        users[i] = datas[i+1];
                    }
                    ChatMainFrame cmf =  new ChatMainFrame(textField.getText(), users,s);
                    cmf.setVisible(true);
                    cmf.setLocationRelativeTo(this);
                    this.dispose();
                }
                                
            } catch (Exception e1) {
                System.out.println(new Date().getTime());
                e1.printStackTrace();
            }
        }
        
    }
}

聊天室主界面

public class ChatMainFrame extends JFrame implements ActionListener,MouseListener,KeyListener{
    
    private String user;
    private Socket socket;
    
    private JPanel contentPane;
    private JTextArea textArea_1;
    private JTable table;
    private DefaultTableModel dtm;
    private JComboBox comboBox;
    private JTextArea textArea;
    private JScrollPane scrollPane_1;
    private JPanel panel_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    String[] users = {"xal","hwy","hyx"};
                    ChatMainFrame frame = new ChatMainFrame("hwy",users,null);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ChatMainFrame(final String user, String[] onlineUser,final Socket s) {
        
        this.user = user;
        this.socket = s;
        try {
            UIManager.setLookAndFeel(new SeaGlassLookAndFeel());
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 400);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        setTitle(user);
        
        JScrollPane scrollPane = new JScrollPane();
        
        scrollPane_1 = new JScrollPane();
        
        JScrollPane scrollPane_2 = new JScrollPane();
        this.addKeyListener(this);
        
        panel_1 = new JPanel();
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 157, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.UNRELATED)
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                        .addComponent(scrollPane_2, GroupLayout.DEFAULT_SIZE, 415, Short.MAX_VALUE)
                        .addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)))
                .addComponent(panel_1, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE)
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                            .addPreferredGap(ComponentPlacement.RELATED)
                            .addComponent(scrollPane_2, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE))
                        .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
        
        JButton btnNewButton = new JButton("发送");
        
        JButton btnNewButton_1 = new JButton("关闭");
        
        comboBox = new JComboBox();
        comboBox.addItem("群聊");
        comboBox.addItem("私聊");
        GroupLayout gl_panel_1 = new GroupLayout(panel_1);
        gl_panel_1.setHorizontalGroup(
            gl_panel_1.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 158, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED, 282, Short.MAX_VALUE)
                    .addComponent(btnNewButton)
                    .addGap(18)
                    .addComponent(btnNewButton_1)
                    .addGap(2))
        );
        gl_panel_1.setVerticalGroup(
            gl_panel_1.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(Alignment.TRAILING, gl_panel_1.createSequentialGroup()
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnNewButton)
                        .addComponent(btnNewButton_1))
                    .addContainerGap())
        );
        panel_1.setLayout(gl_panel_1);
        btnNewButton_1.addActionListener(this);
        btnNewButton.addActionListener(this);
        
        String[][] users = new String[onlineUser.length][];
        String[] cum = {"我的好友"};
        dtm = new DefaultTableModel(users, cum);
        table = new JTable(20,1);
        table.setModel(dtm);
        scrollPane.setViewportView(table);
        for (int i = 0; i < onlineUser.length; i++) {
            dtm.setValueAt(onlineUser[i], i, 0);
        }
        textArea_1 = new JTextArea();
        textArea_1.addKeyListener(this);
        textArea_1.setLineWrap(true);
        scrollPane_2.setViewportView(textArea_1);
        textArea = new JTextArea();
        textArea.setLineWrap(true);
        scrollPane_1.setViewportView(textArea);
        contentPane.setLayout(gl_contentPane);
        
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(s.getOutputStream());
                    Tools.sendData(out, "1010|"+user);
                    out.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }finally{
                    try {
                        out.close();
                        s.close();
                        System.exit(0);
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        });
        
        //启动消息监听器
        new Thread(new MessageListener(textArea, dtm, s, user,table,scrollPane_1)).start();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        Object obj = e.getSource();
        
        if((obj instanceof JLabel)){
            
            JLabel label = (JLabel) obj;
            label.setOpaque(true);
            label.setBackground(new Color(93,12,123));
        }
        
    }

    @Override
    public void mouseExited(MouseEvent e) {
        Object obj = e.getSource();
        
        if((obj instanceof JLabel)){
            
            JLabel label = (JLabel) obj;
            label.setOpaque(false);
            label.setBackground(Color.red);
        }
        
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();
        
        if((obj instanceof JButton)){
            
            JButton button = (JButton) obj;
            if(button.getText().equals("发送")){
                try {
                    String item = (String) comboBox.getSelectedItem();
                    System.out.println(item);
                    if(item.equals("群聊")){
                        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
                        Tools.sendData(out, "1001"+"|"+user+"|"+textArea_1.getText());
                        textArea_1.setText("");
                    }else{
                        int index = table.getSelectedRow();
                        String toUser = (String) dtm.getValueAt(index, 0);
                        textArea.append("你对【"+toUser+"】说:"+textArea_1.getText()+"\r\n");
                        BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
                        Tools.sendData(out, "1002"+"|"+user+"|"+toUser+"|"+textArea_1.getText());
                        textArea_1.setText("");
                        JScrollBar sbar =  scrollPane_1.getVerticalScrollBar();
                        sbar.setValue(sbar.getMaximum());
                    }
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            
            if(button.getText().equals("关闭")){
                
                BufferedOutputStream out = null;
                try {
                    out = new BufferedOutputStream(socket.getOutputStream());
                    Tools.sendData(out, "1010|"+user);
                    out.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }finally{
                    try {
                        out.close();
                        socket.close();
                        System.exit(0);
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println(key);
        if(key == KeyEvent.VK_ENTER){
            try {
                String item = (String) comboBox.getSelectedItem();
                System.out.println(item);
                if(item.equals("群聊")){
                    BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
                    Tools.sendData(out, "1001"+"|"+user+"|"+textArea_1.getText());
                    textArea_1.setText("");
                }else{
                    int index = table.getSelectedRow();
                    String toUser = (String) dtm.getValueAt(index, 0);
                    textArea.append("你对【"+toUser+"】说:"+textArea_1.getText()+"\r\n");
                    BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
                    Tools.sendData(out, "1002"+"|"+user+"|"+toUser+"|"+textArea_1.getText());
                    textArea_1.setText("");
                }
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
            textArea_1.setText("");
        }
        
    }
}

登入监听

public class LoginListener{

    
    public static String login(Socket s ,String msg) {
        try {
            BufferedOutputStream out = new BufferedOutputStream(
                    s.getOutputStream());
            Tools.sendData(out, msg);
            BufferedInputStream in = new BufferedInputStream(s.getInputStream());
            String responsCode = Tools.receiveData(in);
            System.out.println(responsCode);
            return responsCode;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}

用户消息监听

/**
 * 用户消息监听
 * @author huang
 *
 */
public class MessageListener implements Runnable{
    
    private JTextArea jta;
    private Socket s;
    private DefaultTableModel dtm;
    private String user;
    private JTable table;
    private JScrollPane scrollPane;
    public MessageListener(JTextArea jta ,DefaultTableModel dtm,Socket s , String user ,JTable table , JScrollPane scrollPane){
        this.jta = jta;
        jta.setEditable(false);
        this.s =s;
        this.dtm = dtm;
        this.user = user;
        this.table = table;
        this.scrollPane = scrollPane;
    }
    
    @Override
    public void run() {
        try {
            while(true){
                if(s.isClosed()){
                    break;
                }
                BufferedInputStream in = new BufferedInputStream(s.getInputStream());
                String info = Tools.receiveData(in);
//                System.out.println("返回数据:"+info);
                String[] datas = info.split("\\|");
//                System.out.println(datas[0]);
//                System.out.println(datas[0].equals("1000"));
                if(datas[0].equals("1000")){ //登入通知群发显示
                    onlineNotifyInfo(datas[1]);
                }else if(datas[0].equals("1001")){ //群发消息
                    pocketTransmission(datas[1]);
                }else if(datas[0].equals("1010")){ //下线
                    offlineNotifyInfo(datas[1]);
                }else if(datas[0].equals("1002")){ //返回私聊消息
                    privateInfo(datas[1]);
                }
            }
        } catch (Exception e) {
            try {
                s.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    /**
     * 服务返回私聊消息显示
     * @param msg
     */
    private void privateInfo(String msg) {
        jta.setForeground(Color.BLUE);
        jta.append(msg+"\r\n");
    }

    /**
     * 其他用户上线通知返回
     * @param data
     */
    public void onlineNotifyInfo(String data){
        String onLineUser = data.split(" ")[1];
        if(!user.equals(onLineUser)){
            System.out.println("----------------------------------");
            Vector<String> ve = new Vector<String>();
            ve.add(onLineUser);
            dtm.addRow(ve.toArray());
            table.repaint();
        }
        jta.setForeground(Color.BLUE);
        jta.append(data+"\r\n");
        JScrollBar sbar =  scrollPane.getVerticalScrollBar();
        sbar.setValue(sbar.getMaximum());
    }
    
    /**
     * 获取显示其他用户群发的消息
     * @param data
     */
    public void pocketTransmission(String data){
        jta.setForeground(Color.BLUE);
        jta.append(data+"\r\n");
        JScrollBar sbar =  scrollPane.getVerticalScrollBar();
        sbar.setValue(sbar.getMaximum());
    }
    
    
    /**
     * 其他用户下线通知返回
     */
    public void offlineNotifyInfo(String data) {
        Vector ve = dtm.getDataVector();
        for (int i = 0; i < ve.size(); i++) {
            System.out.println(data + "," + dtm.getValueAt(i, 0));
            if (data.equals(dtm.getValueAt(i, 0))) {
                dtm.removeRow(i);
                table.repaint();
            }
        }
        jta.setForeground(Color.BLUE);
        jta.append(data+"退出了聊天室\r\n");
        JScrollBar sbar =  scrollPane.getVerticalScrollBar();
        sbar.setValue(sbar.getMaximum());
    }
}

socket客户端

public class MyClient {
    
    public static Socket connect(String ip , int port) throws Exception{
        System.out.println(new Date().getTime());
        Socket s = new Socket(ip,port);
        //s.setSoTimeout(60000);
        return s;
    }
    
    /**
     * 将消息的长度值,转换成4位数,并依此放入byte数组中
     * @param msg
     * @return
     */
    public static byte[] getMsgLength(int length){
        
        byte[] bt = new byte[4];
        bt[0] = (byte) (length/1000);
        bt[1] = (byte) (length%1000/100);
        bt[2] = (byte) (length%100/10);
        bt[3] = (byte) (length%10);
        
        return bt;
    }
    
/*    public static void main(String[] args) {
        
        byte[] bt = getMsgLength(5624);
        
        for (int i = 0; i < bt.length; i++) {
            System.out.println(bt[i]);
        }
        
    }*/
    
    protected  static int readMsgHead(BufferedInputStream in) throws IOException{
        int length = 0;
        byte[] bt = new byte[4];
        in.read(bt, 0, 4);
        length = bt[0]*1000+bt[1]*100+bt[2]*10+bt[3];
        return length;
    }
}

工具类

public class Tools {
    
    protected static byte[] getMsgLength(int length){
        System.out.println("返回数据");
        byte[] bt = new byte[4];
        bt[0] = (byte) (length/1000);
        bt[1] = (byte) (length%1000/100);
        bt[2] = (byte) (length%100/10);
        bt[3] = (byte) (length%10);
        
        return bt;
    }
    
    public static void sendData(BufferedOutputStream out,String message) throws Exception{
        byte[] head = Tools.getMsgLength(message.getBytes("UTF-8").length);
        out.write(head);
        out.flush();
        out.write(message.getBytes("UTF-8"));
        out.flush();
    }
    
    public static String  receiveData(BufferedInputStream in) throws Exception{
        int length = readMsgHead(in);
        System.out.println("接收到的数据长度:"+length);
        byte[] bt = new byte[length];
        in.read(bt);
        String data = new String(bt,"UTF-8");
        return data;
    }
    
    
    
    protected  static int readMsgHead(BufferedInputStream in) throws IOException{
        int length = 0;
        byte[] bt = new byte[4];
        in.read(bt, 0, 4);
        length = bt[0]*1000+bt[1]*100+bt[2]*10+bt[3];
        return length;
    }
    
    
}

 

聊天室客户端实现

标签:line   input   cal   extend   stream   ase   trace   final   pre   

原文地址:http://www.cnblogs.com/hwyblog/p/7875627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!