java 简单的聊天工具 (带界面的)

首先建立一个工程 导入数据库驱动

工程图 这里写图片描述

java 简单的聊天工具 (带界面的)_第1张图片

解释一下 entity包是 bin目录 Message包下 和 User包下 是对象相关的操作

这里写图片描述

Message 
package com.FakeQQ.entity;

import java.util.Date;

public class Message {

    //需要序列化发送,所以要继承Serializable接口
        private int id;
        private String content;
        private int sender;
        private int receiver;
        private Date sendTime;
        private Date receiveTime;
        private int state;
        private int ip;

        public int getIp() {
            return ip;
        }
        public void setIp(int ip) {
            this.ip = ip;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getContent() {
            return content;
        }
        public void setContent(String content) {
            this.content = content;
        }
        public int getSender() {
            return sender;
        }
        public void setSender(int sender) {
            this.sender = sender;
        }
        public int getReceiver() {
            return receiver;
        }
        public void setReceiver(int receiver) {
            this.receiver = receiver;
        }
        public Date getSendTime() {
            return sendTime;
        }
        public void setSendTime(Date sendTime) {
            this.sendTime = sendTime;
        }
        public Date getReceiveTime() {
            return receiveTime;
        }
        public void setReceiveTime(Date receiveTime) {
            this.receiveTime = receiveTime;
        }
        public int getState() {
            return state;
        }
        public void setState(int state) {
            this.state = state;
        }
    }


User 
package com.FakeQQ.entity;

import java.util.Date;

public class User {


        //这叫实体bin
        private int qqNumber;
        private String qqName;
        private String qqPassword;
        private Date registTime; //注册时间
        private String sex;
        private String introduce; //个人简介
        private String ip;
        public int getQqNumber() {
            return qqNumber;
        }
        public void setQqNumber(int qqNumber) {
            this.qqNumber = qqNumber;
        }
        public String getQqName() {
            return qqName;
        }
        public void setQqName(String qqName) {
            this.qqName = qqName;
        }
        public String getQqPassword() {
            return qqPassword;
        }
        public void setQqPassword(String qqPassword) {
            this.qqPassword = qqPassword;
        }
        public Date getRegistTime() {
            return registTime;
        }
        public void setRegistTime(Date registTime) {
            this.registTime = registTime;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public String getIntroduce() {
            return introduce;
        }
        public void setIntroduce(String introduce) {
            this.introduce = introduce;
        }
        public String getIp() {
            return ip;
        }
        public void setIp(String ip) {
            this.ip = ip;
        }



    }

java 简单的聊天工具 (带界面的)_第2张图片

MessageDaoImpl.java

package com.FakeQQ.Message.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.FakeQQ.entity.Message;
import com.FakeQQ.util.ConnectionUtil;

public class MessageDaoImpl {

    public int SaveMessage(Message message) {
        Connection con=null;
        PreparedStatement pstm=null;
        int key=0;
        try{
            con=ConnectionUtil.getCon();
            pstm=con.prepareStatement(
                    "insert into message(content,sender,receiver,"
                    + "sendTime,state)values(?,?,?,?,?)",
                    Statement.RETURN_GENERATED_KEYS);
            pstm.setString(1, message.getContent());//
            pstm.setInt(2, message.getSender());
            pstm.setInt(3, message.getReceiver());
            pstm.setString(4, message.getSendTime().toLocaleString());
            pstm.setInt(5, message.getState());
            pstm.executeUpdate();
            ResultSet rs=pstm.getGeneratedKeys();

            if(rs.next())
                key = rs.getInt(1);
            return key;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
            // TODO: handle exception
        }finally{
            ConnectionUtil.closeCon(null, pstm, con);
        }

    }
}

ClientThread.java

package com.FakeQQ.Message.service;

import java.io.OutputStream;
import java.net.Socket;

import com.FakeQQ.entity.Message;
import com.FakeQQ.util.SeralizableUtil;

public class ClientThread implements Runnable {
    Message message;
    String ip;
    public ClientThread(Message message,String ip) {
        this.message=message;
        this.ip=ip;
    }

    @Override
    public void run() {

        try {

            Socket socket = new Socket(ip,8888);
            OutputStream os = socket.getOutputStream();

            byte cache[]= SeralizableUtil.SerializableMessage(message);
            os.write(cache);
            os.flush();
            os.close();
            System.out.println(cache.length);
            //socket.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}


MessageServiceImpl.java

package com.FakeQQ.Message.service;

import com.FakeQQ.Message.dao.MessageDaoImpl;
import com.FakeQQ.entity.Message;

public class MessageServiceImpl {
    public int sendMessage(Message msg){
        MessageDaoImpl messageDaoImpl=new MessageDaoImpl();
        return messageDaoImpl.SaveMessage(msg);
    }
}

ServerThread.java

package com.FakeQQ.Message.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Iterator;

import com.FakeQQ.Message.view.MessageFrame;
import com.FakeQQ.entity.Message;
import com.FakeQQ.user.view.MainFrame;
import com.FakeQQ.util.SeralizableUtil;
import com.FakeQQ.util.SerializableUtilRe;

public class ServerThread implements Runnable {

    MainFrame mainFrame;
    public ServerThread(MainFrame mainFrame) {
        this.mainFrame=mainFrame;
    }
    @Override
    public void run() {
        try {
            ServerSocket server = new ServerSocket(8888);
            while(true){
                Socket socket = server.accept();
                InputStream is = socket.getInputStream();
                System.out.println("ServerThread已开启");

                //System.out.println(is);
                //if(true) {
                    System.out.println(is.available());
                    byte[] bytes = new byte[is.available()];

                    is.read(bytes);

                    //System.out.println(bytes.length);

                    Message message = SerializableUtilRe.SerializableMessageRe(bytes);

                    System.out.println(message==null);
                    System.out.println(message.getContent());
                    is.close();

                    System.out.println(message.getSender());
                    System.out.println(message.getContent());
                    //  TODO 接受消息并放置到文本框中
                    Iterator i = mainFrame.MessageFrames.keySet().iterator();

                    boolean isExit = false;
                    while(i.hasNext()) {
                        int key = Integer.parseInt(i.next().toString());
                        if(message.getSender()== key) {

                            MessageFrame messageFrame = mainFrame.MessageFrames.get(key);
                            String content = messageFrame.txtList.getText();
                            messageFrame.txtList.setText(content + messageFrame.another.getQqName()+ ":" + message.getContent() );
                            isExit=true;
                            break;
                        }
                    //}
                    if(!isExit) {
                        MessageFrame messageFrame = new MessageFrame(mainFrame.myself,message.getSender() + "JK ");
                        mainFrame.MessageFrames.put(message.getSender(),messageFrame);
                    }

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

}

BtnListener.java
package com.FakeQQ.Message.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

import com.FakeQQ.Message.service.ClientThread;
import com.FakeQQ.Message.service.MessageServiceImpl;
import com.FakeQQ.entity.Message;

public class BtnListener implements ActionListener {
    private MessageFrame messageFrame;
     public BtnListener(MessageFrame messageFrame) {
         this.messageFrame = messageFrame;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        // 获得文本框值
        String msg = messageFrame.txtMsg.getText();
        //实例化Message对象 并存入数据库
        Message message = new Message();
        message.setContent(msg);
        message.setSender(messageFrame.myself.getQqNumber());
        message.setReceiver(messageFrame.another.getQqNumber());
        message.setSendTime(new Date());
        message.setState(1);

        MessageServiceImpl messageServiceImpl = new MessageServiceImpl();
        int key = messageServiceImpl.sendMessage(message);
        message.setId(key);
        //启动线程 发送给对方
        new Thread(new ClientThread(message,messageFrame.another.getIp())).start();
        messageFrame.txtMsg.setText("");


        // 将消息放到本窗口多行文本框

        String content=messageFrame.txtList.getText();
        int size = messageFrame.txtList.getWidth()/4;
        int spaceSize = size-messageFrame.myself.getQqName().length()-1;
        if(spaceSize>0) {
            for(int i=0;i
                content += " ";
            }
        }
        content += messageFrame.myself.getQqName()+":"+msg+"\n";
        messageFrame.txtList.setText(content);
    }

}

MessageFrame.java
package com.FakeQQ.Message.view;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;

import com.FakeQQ.entity.User;
import com.FakeQQ.user.service.UserServiceImpl;

public class MessageFrame extends JFrame{
    public User myself;
    public User another;

    public JTextArea txtList=null;
    public JTextField txtMsg=null;
    public JButton btn=null;

    public MessageFrame(User myself, String other){
        this.myself=myself;
        String temp[]=other.split(" ");
        UserServiceImpl userServiceImpl=new UserServiceImpl();
        another=userServiceImpl.listByQqNum(Integer.parseInt(temp[0]));
        JPanel panel=new JPanel();
        this.getContentPane().add(panel);
        panel.setLayout(new BorderLayout());

        txtList=new JTextArea(5, 20);
        panel.add(txtList, BorderLayout.CENTER);

        JPanel txtPanel=new JPanel();
        txtMsg=new JTextField(10);
        btn=new JButton("发送");

        btn.addActionListener(new BtnListener(this));

        txtPanel.add(txtMsg);
        txtPanel.add(btn);
        panel.add(txtPanel, BorderLayout.SOUTH);

        this.setTitle(temp[1]);
        this.setSize(400,300);
        this.setVisible(true);

    }
}

java 简单的聊天工具 (带界面的)_第3张图片

“`
UserDaoImpl.java
package com.FakeQQ.user.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.FakeQQ.entity.User;
import com.FakeQQ.util.ConnectionUtil;

public class UserDaoImpl {

public User getUser(int qqNum){
    User u = new User(); 
    try{
        //获取数据库连接
        Connection con=ConnectionUtil.getCon();
        //创建statement
        PreparedStatement pstm=con.prepareStatement(
                "select * from user u where u.qqNumber=?");
        //设置参数,针对?占位符
        pstm.setInt(1, qqNum);
        //执行sql语句
        ResultSet rs=pstm.executeQuery();


        if(rs.next()) {
            System.out.println(rs.getInt(1));
            u.setQqNumber(rs.getInt(1));
            System.out.println(rs.getString(2));
            u.setQqName(rs.getString(2));
            u.setQqPassword(rs.getString(3));
            u.setRegistTime(rs.getDate(4));
            u.setSex(rs.getString(5));
            u.setIntroduce(rs.getString(6));
            u.setIp(rs.getString(7));

        }
        //关闭连接
        ConnectionUtil.closeCon(rs, pstm, con);
        return u;
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}









//用户注册
public boolean saveUser(User u) { 
    try {
        //1,加载驱动类
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取数据库连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myqq_db","root","");
        //3.数据库实际操作
        PreparedStatement pstm = con.prepareStatement(
                "insert into user(qqName,qqPassword, registTime,sex,introduce,ip)"
                + " values(?,?,?,?,?,?)" );
        pstm.setString(1, u.getQqName());
        pstm.setString(2, u.getQqPassword());
        pstm.setString(3, u.getRegistTime().toLocaleString());
        pstm.setString(4, u.getSex());
        pstm.setString(5, u.getIntroduce());
        pstm.setString(6,u.getIp());


        int count = pstm.executeUpdate(); // 插入之后做更新数据

        pstm.close();
        con.close();
        if (count >0)
            return true;
        else
            return false;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


// 找到某一账户,返回这个账户的所有资料
public User findByNameAndPassword(int qqNumber,String password) {

    User u = new User();
    try {


        //1,加载驱动类
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取数据库连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myqq_db","root","");
        //3.数据库具体操作
        PreparedStatement pstm = con.prepareStatement(
                "select * from user u  where u.qqNumber = ? and u.qqPassword = ? " );

        pstm.setInt(1,qqNumber);
        pstm.setString(2, password);

        ResultSet rs = pstm.executeQuery(); //查找之后返回集合

        if(rs.next()) {
            u.setQqNumber(rs.getInt(1));
            u.setQqName(rs.getString(2));
            u.setQqPassword(rs.getString(3));
            u.setRegistTime(rs.getDate(4));
            u.setSex(rs.getString(5));
            u.setIntroduce(rs.getString(6));
            u.setIp(rs.getString(7));

        }
        pstm.close();
        con.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

    return u;


}

 // 通过qq号查找所有好友(默认数据库所有用户都是好友)
public List  findAllFriends(int qqNumber) {
    ResultSet rs=null;
    PreparedStatement pstm = null;
    Connection con = null;


    List  list = new ArrayList ();
    try {
        con = ConnectionUtil.getCon();
        pstm = con.prepareStatement(
                "select * from user u where u.qqNumber<>?"
                );
        pstm.setInt(1, qqNumber);
        rs = pstm.executeQuery();

        while(rs.next()) {
            User u = new User();
            u.setQqNumber(rs.getInt(1));
            u.setQqName(rs.getString(2));
            u.setQqPassword(rs.getString(3));
            u.setRegistTime(rs.getDate(4));
            u.setSex(rs.getString(5));
            u.setIntroduce(rs.getString(6));
            u.setIp(rs.getString(7));
            list.add(u);
        }
        return list;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }finally {
        ConnectionUtil.closeCon(rs,pstm,con);

    }

}

// 对特定的QQ号做密码重置
public boolean updatePassword(int qqNumber,String qqPassword) {
    ResultSet rs=null;
    PreparedStatement pstm = null;
    Connection con = null;

    try {
        con = ConnectionUtil.getCon();
        pstm = con.prepareStatement(
                "update user set qqPassword=? where qqNumber=?"
                );
        pstm.setString(1,qqPassword);
        pstm.setInt(2, qqNumber);

        int count = pstm.executeUpdate();
        if(count>0) {
            return true;
        }

    } catch (Exception e) {
        return false;
    }finally {
        ConnectionUtil.closeCon(rs,pstm,con);
    }
    return false;
}


// 登录成功后修改IP地址
public void updateIp(int qqNum,String qqIp) {
    ResultSet rs=null;
    PreparedStatement pstm = null;
    Connection con = null;

    try {
        con = ConnectionUtil.getCon();
        pstm = con.prepareStatement(
                "update user set ip=? where qqNumber=?"
                );
        pstm.setString(1,qqIp);
        pstm.setInt(2, qqNum);

        int count = pstm.executeUpdate();


    } catch (Exception e) {

    }finally {
        ConnectionUtil.closeCon(rs,pstm,con);
    }

}

}

UserServiceImpl.java
package com.FakeQQ.user.service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

import com.FakeQQ.entity.User;
import com.FakeQQ.user.dao.UserDaoImpl;

public class UserServiceImpl {
// 用户注册
public boolean regist(User u) {
u.setRegistTime(new Date());
UserDaoImpl userDaoImpl = new UserDaoImpl();
return userDaoImpl.saveUser(u);
}

// 查找 好友
public List listFriends(int qqNumber) {
    UserDaoImpl userDaoImpl = new UserDaoImpl();
    return userDaoImpl.findAllFriends(qqNumber);


}

// 用户登录
// 通过qq号码和密码查找 某一用户
public User login(int qqNum, String password){
    UserDaoImpl userDaoImpl=new UserDaoImpl();
    User u =  userDaoImpl.findByNameAndPassword(qqNum, password);
    if(u!=null) {
        // 获得 本地 IP
            try {
                String ip =  InetAddress.getLocalHost().toString();
                // 修改 数据库 IP
                userDaoImpl.updateIp(qqNum, ip);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }
    return u;
}

public User listByQqNum(int qqNum){
    UserDaoImpl userDaoImpl=new UserDaoImpl();
    return userDaoImpl.getUser(qqNum);
}

}

BtnLoginListener.java

// QQ登录监听函数

package com.FakeQQ.user.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.FakeQQ.entity.User;
import com.FakeQQ.user.service.UserServiceImpl;

public class BtnLoginListener implements ActionListener{

LoginFrame loginFrame;
public BtnLoginListener(LoginFrame loginFrame) {
    this.loginFrame = loginFrame;
}

public void actionPerformed(ActionEvent e){
    String values = e.getActionCommand();

    if(values.equals("确定")) {
    String qqNum = loginFrame.txtqqNum.getText();
    String password = new String (loginFrame.txtPassword.getPassword());
    UserServiceImpl userServiceImpl = new UserServiceImpl();
    User user = new User();
    user = userServiceImpl.login(Integer.parseInt(qqNum),password);
    if(user!=null) {
        //System.out.println("登录成功!");
        // new JTree
        loginFrame.dispose();
        loginFrame=null;
        MainFrame mainFrame = new MainFrame(user);
    }

    }else if(values.equals("取消")) {
        System.exit(0);
    }

}

}

BtnResigerListener.java
package com.FakeQQ.user.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.FakeQQ.entity.User;
import com.FakeQQ.user.service.UserServiceImpl;

public class BtnResigerListener implements ActionListener {
private ResigerFrame resigerframe = null;

public BtnResigerListener(ResigerFrame resigerframe) {
    this.resigerframe = resigerframe;
}
public void actionPerformed(ActionEvent e) {
    User user = new User();
    String qqName = resigerframe.txtqqName.getText();
    String sex = resigerframe.txtSex.getText();
    String qqNum = resigerframe.txtqqNum.getText();
    String password = new String (resigerframe.txtPassword.getPassword());
    String introduce = resigerframe.txtIntroduce.getText();

    user.setQqName(qqName);
    user.setSex(sex);

// user.setQqNumber(Integer.parseInt(qqNum));
user.setQqPassword(password);
user.setIntroduce(introduce);
UserServiceImpl userServiceImpl = new UserServiceImpl();
boolean flag = userServiceImpl.regist(user);
if(flag==true) {
// System.out.println(“注册成功!”);

    }
}

}

LoginFrame.java

“`package com.FakeQQ.user.view;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class LoginFrame extends JFrame {
JLabel lblqqNum;
JLabel lblqqPassword;
JTextField txtqqNum;
JPasswordField txtPassword;
JButton btnLogin;
JButton btnCancle;
JButton btnResiger;

// 构造方法
public LoginFrame() {
    lblqqNum = new JLabel("QQ号");
    lblqqPassword = new JLabel("密码:");
    txtqqNum = new JTextField();
    txtPassword = new JPasswordField("");
    btnLogin = new JButton("确定");
    btnCancle = new JButton("取消");
    btnResiger = new JButton("QQ注册");

    this.getContentPane().setLayout(null); //布局为自己
    this.getContentPane().add(lblqqNum);
    lblqqNum.setBounds(20,20,80,20);

    this.getContentPane().add(lblqqPassword);
    lblqqPassword.setBounds(20,50,80,20);


    this.getContentPane().add(txtqqNum);
    txtqqNum.setBounds(70,20,140,20);

    this.getContentPane().add(txtPassword);
    txtPassword.setBounds(70,50,140,20);


    this.getContentPane().add(btnLogin);
    btnLogin.setBounds(60,80,80,20);

    this.getContentPane().add(btnCancle);
    btnCancle.setBounds(160,80,80,20);

    this.getContentPane().add(btnResiger);
    btnResiger.setBounds(100,130,90,20);


    BtnLoginListener btnLoginListener = new BtnLoginListener(this);
    btnLogin.addActionListener(btnLoginListener); //事件源和事件者关联起来
    btnCancle.addActionListener(btnLoginListener);



     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口的时候退出应用程序
    //设置窗口居中显示
      //定义一个工具包
      Toolkit kit = Toolkit.getDefaultToolkit();//获得屏幕大小尺寸
      Dimension screenSize = kit.getScreenSize();
      int screenWidth = screenSize.width;//获得屏幕宽度
      int screenHeight = screenSize.height;//获得屏幕高度;
      int i = this.getWidth();//获得当前窗体的宽度
      int j = this.getHeight();//获得当前窗体的高度
      this.setLocation((screenWidth-i)/2, (screenHeight-j)/2);


    this.setTitle("QQ登录");
    this.setSize(300,200); 
    this.setVisible(true); // 可见


}

}

MainFrame.java
package com.FakeQQ.user.view;

import java.util.HashMap;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

import com.FakeQQ.Message.service.ServerThread;
import com.FakeQQ.Message.view.MessageFrame;
import com.FakeQQ.entity.User;
import com.FakeQQ.user.dao.UserDaoImpl;
import com.FakeQQ.user.service.UserServiceImpl;

public class MainFrame extends JFrame{
public User myself;
public List friends;
public HashMap

你可能感兴趣的:(Java小白之路)