Java教程

2021-06-14:java聊天软件编写

本文主要是介绍2021-06-14:java聊天软件编写,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

客户端代码:

界面代码存放于client_view包中。

登录界面:

package client_view;
import client_model.Clientlogin;
import common.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//客户端登录界面
public class Login extends JFrame  {
    //顶部组件
    public JLabel jbl1;
    //中心组件
    public   JTabbedPane jtp;
    public  JPanel P1,p2,p3;
    public  JPanel P1_p1,P1_p2,P1_p3,P1_p4;
    public  JLabel P1_jla1,P1_jla2,P1_jla3,P1_jla4,P1_jla5,P1_jla6,P1_jla7,P1_jla8;//号码标签,密码标签,
    public  JButton P1_jb1;
    public  JTextField P1_jte1;//账号输入条
    public JPasswordField P1_jPa1;//密码输入条
    public  JCheckBox P1_box1,P1_box2;//勾选项
    //底部组件
    public  JPanel jp1;
    public  JButton jbl3_1, jbl3_2, jbl3_3;
    //监听器
    public  Loginlistener listener1;
    //后台
    public   Clientlogin client;
    public static void main(String[] args) {

        Login login = new Login();
    }
    public Login() {
        this.setTitle("趣说");
        //顶部背景图
        jbl1 = new JLabel(new ImageIcon("image/顶部背景.png"));
        client=new Clientlogin(this);
        listener1=new Loginlistener(this,client);
        //中部选项卡管理、
        P1=new JPanel(new GridLayout(3,3));
        P1_p1=new JPanel(new GridLayout(1,2));
        P1_p2=new JPanel(new GridLayout(1,2));
        P1_p3=new JPanel(new GridLayout(1,2));
        P1_jla1=new JLabel("账号",JLabel.CENTER);
        P1_jla2=new JLabel("密码",JLabel.CENTER);
        P1_jla3=new JLabel("找回密码",JLabel.CENTER);
        P1_jla3.setForeground(Color.blue);
        P1_jla4=new JLabel("帮助");
        P1_jla4.setForeground(Color.blue);
        P1_jla5=new JLabel("注册账号",JLabel.RIGHT);
        P1_jla5.addMouseListener(listener1);
        P1_jla5.setForeground(Color.blue);
        P1_jla6=new JLabel();
        P1_jla7=new JLabel();
        P1_jla8=new JLabel();
        P1_jte1=new JTextField();
        P1_jPa1=new JPasswordField();
        P1_box1=new JCheckBox("自动登录");
        P1_box2=new JCheckBox("记住密码");
        P1.add(P1_jla1);
        P1.add(P1_jte1);
        P1.add(P1_jla6);
        P1.add(P1_jla2);
        P1.add(P1_jPa1);
        P1.add(P1_jla7);
        P1_p1.add(P1_box2);
        P1_p1.add(P1_jla5);
        P1_p2.add(P1_jla3);
        P1_p2.add(P1_jla4);
        P1_p3.add(P1_jla8);
        P1_p3.add(P1_box1);
        P1.add(P1_p3);
        P1.add(P1_p1);
        P1.add(P1_p2);
        this.add(P1,"Center");
        //底部登录控件
        jp1=new JPanel();
        jbl3_1=new JButton(new ImageIcon("image/登录.png"));
        System.out.println("登录后台建立成功");
        System.out.println("登录监听建立成功");
        jbl3_1.addActionListener(listener1);
        jp1.add(jbl3_1);
        this.add(jp1,"South");
        this.add(P1,"Center");
        this.add(jbl1, "North");
        this.setBounds(750,380,470, 337);
        this.setResizable(false);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

注册界面:

package client_view;
import javax.swing.*;
import java.awt.*;
import client_model.*;
public class Register_window extends JFrame {
   public JTextField username;
  public   JTextField id;
  public   JPasswordField password;
    JButton jb1,jb2;
    JPanel jp;
JLabel jl1,jl2,jl3;

Registerlistener listener;
Register register;
    public  Register_window(Register r)
    {
        register=r;
        username=new JTextField();
        id=new JTextField();
        password =new JPasswordField();
        listener=new Registerlistener(this,register);
        jb1=new JButton("取消");
        jb1.addActionListener(listener);
        jb2=new JButton("注册");
        jb2.addActionListener(listener);
        jl1=new JLabel("用户名:");
        jl2=new JLabel("账号:");
        jl3=new JLabel("密码:");
        jp=new JPanel(new GridLayout(4,2));
        jp.add(jl1);
        jp.add(username);
        jp.add(jl2);
        jp.add(id);
        jp.add(jl3);
        jp.add(password);
        jp.add(jb1);
        jp.add(jb2);
        this.setName("注册");
        this.add(jp);
        this.setBounds(750,380,470, 337);
        this.setResizable(false);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}

好友列表界面:

package client_view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;

import client_model.*;
import common.Friend;
import common.Friendslist;
import common.Online;
import common.User;

//好友列表
public  class Friend_list_window extends JFrame  {
   public JPanel jp1,jp1_1,jp2;//1.好友
    JButton jb1,jb2;
    JScrollPane jsc1;
    //群聊主键
    JPanel jpq1,jpq1_1,jpq2;
    JButton jbq1,jbq2;
    JScrollPane jscq1;
    JLabel jbl1,jbl2_1,jbl2_2;//添加好友 创建群聊,加入群聊
   public Friend_list_listener listener;
    Friend_list list;
    public String ID;
    public String Username;
   public Chat_window chatWindow[];
   public JLabelclass[] jlac;
   public JLabel[] jla;
   public Online olf;
    public Addfriend addfriend;
    CardLayout card=new CardLayout();
    Friendslist friendlist;
    Client_link server;
    public static void main(String[] args) {
           }
    public Friend_list_window(String UserID, String name, Friend_list l, Friendslist flist, Client_link s, Online onlf)
    {
        olf=onlf;
        Username=name;
        list=l;
        ID=UserID;
        server=s;
        this.setTitle(Username);
        friendlist=flist;
        //第一张卡片 好友列表
        listener=new Friend_list_listener(list,this);
        jp1=new JPanel(new BorderLayout());
        int n=friendlist.getFriends().size();
        System.out.println("好友数"+n);
        jp1_1=new JPanel(new GridLayout(n+20,1,4,4));//好友列表容器
        jb1=new JButton("我的好友");
        jbl1=new JLabel("添加好友");
        jbl1.addMouseListener(listener);
        jp1_1.add(jbl1);
         jla=new JLabel[n];
         jlac=new JLabelclass[n];
         chatWindow=new Chat_window[jla.length];
        addfriend=new Addfriend(list);
        int i=0;
        Collection values = friendlist.getFriends().values();  //获取Map集合的value集合
        for(Object object:values){
            Friend f=(Friend) object;
            jla[i]=new JLabel(f.getName(),new ImageIcon("image/头像.png"),JLabel.LEFT);
            jlac[i]=new JLabelclass(jla[i],f.getId(),Username,f.getName());
           if(olf.onlinelist.containsKey(jlac[i].ID)){
              String title=f.getName()+" (在线)";
               jla[i].setText(title);
           }
            jla[i].addMouseListener(listener);
            jp1_1.add(jla[i]);
            chatWindow[i]=new Chat_window(jla[i].getText(),jlac[i].ID,ID,server,Username);
            i++;
        }
        jsc1=new JScrollPane(jp1_1);
        jp2=new JPanel(new BorderLayout());
        jb2=new JButton("群聊");
        jb2.addActionListener(listener);
        jp2.add(jb2);
        jp1.add(jb1,"North");
        jp1.add(jsc1,"Center");
        jp1.add(jb2,"South");
        //群聊卡片
        jpq1=new JPanel(new BorderLayout());
        jpq1_1=new JPanel(new GridLayout(23,1,4,4));//好友列表容器
        jbq1=new JButton("我的好友");
        jbq1.addActionListener(listener);
        jbl2_1=new JLabel("创建群聊");
        jpq1_1.add(jbl2_1);
        jbl2_2=new JLabel("加入群聊");
        jpq1_1.add(jbl2_2);
        JLabel[] jlaq=new JLabel[5];
        for (int j=0;j<jlaq.length;j++){
            jlaq[j]=new JLabel(j+1+"",new ImageIcon("image/群头像.png"),JLabel.LEFT);
            jlaq[j].addMouseListener(listener);
            jpq1_1.add(jlaq[j]);
        }
        jscq1=new JScrollPane(jpq1_1);
        jpq2=new JPanel(new BorderLayout());
        jbq2=new JButton("群聊");
        jpq2.add(jbq1,"North");
        jpq2.add(jbq2,"South");
        jpq1.add(jpq2,"North");
        jpq1.add(jscq1,"Center");
        //创建界面
        this.setLayout(card);
        this.add(jp1,"1");
        this.add(jpq1,"2");
        this.setBounds(1300,200,330,700);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

对话窗口界面:

package client_view;
import client_model.Client_Chat;
import client_model.Client_link;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Chat_window extends JFrame  {
    public JButton jb1,jb2;
    public JPanel jp1;
    public  JTextArea jt1,jt2;
    public Client_Chat Clientchat;
    public  Chat_windowlistener listener1;
    public String OwnerId;
    public String friendID;
    public Client_link server;
    public String hostname;
   public Chat_window(String Name,String id,String Owner,Client_link s,String name)
    {
        hostname=name;
        server=s;
        OwnerId=Owner;
        friendID=id;
        jb1=new JButton("发送");
        jb2=new JButton("其他");
        jp1=new JPanel();
        jp1.setLayout(null);
        jt1=new JTextArea();
        jt2=new JTextArea();
        jt1.setBounds(5,5,574,300);
        jt2.setBounds(5,310,574,110);
        jb1.setBounds(374,426,100,30);
        jb2.setBounds(479,426,100,30);
        jp1.add(jb1);
        jp1.add(jb2);
        jp1.add(jt1);
        jp1.add(jt2);
        Clientchat=new Client_Chat(this,server);
        listener1=new Chat_windowlistener(Clientchat);
        jb1.addActionListener(listener1);
        this.setTitle(Name);
        this.add(jp1);
        Random r= new Random();

        this.setBounds(750+r.nextInt(100),380+r.nextInt(50),600, 500);
        this.setResizable(false);
        this.setVisible(false);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    }
}

好友添加界面:

package client_view;

import client_model.Addfriend;

import javax.swing.*;
import java.awt.*;

public class Addfriend_windows extends JFrame {

Addfriend addfriend;
   public JTextField idinput;
   public JButton jb1,jb2;
   public JLabel jla;
  public   JPanel jp;
   public Addfriend_listener listener;
 public    Addfriend_windows(Addfriend af){
     addfriend=af;
        listener=new Addfriend_listener(addfriend,this);
        jp=new JPanel(new GridLayout(2,2));
        jla=new JLabel("账号");
        idinput=new JTextField();
        jb1=new JButton("取消");
        jb2=new JButton("添加");
        jb2.addActionListener(listener);
        jp.add(jla);
        jp.add(idinput);
        jp.add(jb1);
        jp.add(jb2);
        this.setTitle("添加好友");
        this.add(jp);
        this.setBounds(650,280,470, 337);
        this.setResizable(false);
        this.setVisible(false);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

}

 各界面的监听器:存放于client_view包中。

登录界面监听器:

package client_view;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import common.User;
import client_model.*;
import javax.swing.*;
//登录界面监听
public class Loginlistener extends JFrame implements ActionListener, MouseListener {
    Clientlogin loginclient;
    Login window;
    Loginlistener(Login w,Clientlogin c)
    {
        window=w;
        loginclient=c;
        System.out.println("后台传递完成");
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==window.jbl3_1) {
            loginclient.check_login();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==1)
        {
          new Register(window.client);
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        JLabel j1=(JLabel) e.getSource();
        j1.setForeground(Color.LIGHT_GRAY);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        JLabel j1=(JLabel) e.getSource();
        j1.setForeground(Color.black);
    }
}

注册界面监听器:

package client_view;

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

import client_model.*;
import common.*;

public class Registerlistener implements ActionListener {
    Register register;
    Register_window window;

    Registerlistener(Register_window w, Register r) {
        register = r;
        window = w;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == window.jb1) {

            window.dispose();
        }
        if (e.getSource() == window.jb2) {
            register.Registersend();

        }

    }
}

好友列表界面监听器:

package client_view;
import client_model.Friend_list;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import common.*;
public class Friend_list_listener implements ActionListener , MouseListener {
    Friend_list list;
    Friend_list_window window;
    Friend_list_listener(Friend_list l,Friend_list_window w)
    {
        list=l;
        window=w;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==window.jbq1)
        {
            window.card.show(window.getContentPane(),"1");
        }
        if (e.getSource()==window.jb2)
         {
             window.card.show(window.getContentPane(),"2");
         }

    }


    public void mouseClicked(MouseEvent e) {
        int i;
        int flag = 0;
        for (i = 0; i < window.jla.length; i++) {
            if (e.getSource() == window.jla[i]) {
                flag = 1;
                break;
            }
        }
        if (e.getClickCount() == 2 && e.getButton() == 1) {

            if (e.getSource() == window.jbl1) {
                window.addfriend.window.setVisible(true);
            }

            if (flag == 1) {
                if (e.getSource() == window.jla[i]) {
                    window.chatWindow[i].setVisible(true);
                }
            }


        }
        if (e.getButton() == 3) {
            int n = JOptionPane.showConfirmDialog(window, "是否删除该好友?", "删除好友", JOptionPane.YES_NO_OPTION);
            if (n == JOptionPane.YES_OPTION) {
                massage m = new massage();
                m.setType("4");
                m.setSender(window.ID);
                m.setGetter(window.jlac[i].ID);
                System.out.println("删除" + window.jlac[i].jla.getText());
                window.server.deletfriend(m);
            }

        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        JLabel j1 = (JLabel) e.getSource();
        j1.setForeground(Color.LIGHT_GRAY);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        JLabel j1 = (JLabel) e.getSource();
        j1.setForeground(Color.black);
    }
}

聊天会话窗口监听器:

package client_view;

import client_model.Client_Chat;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import common.massage;

//聊天界面监听
public class Chat_windowlistener extends JFrame implements ActionListener {
    Chat_window window;
    Client_Chat clientchat;
    massage textmassage;

    Chat_windowlistener(Client_Chat chat) {
        clientchat = chat;
    }

    public void actionPerformed(ActionEvent e) {
        clientchat.sendmassage();
    }
}

好友添加界面监听器:

package client_view;

import client_model.Addfriend;
import client_model.Register;

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

public class Addfriend_listener implements ActionListener {
    Addfriend addfriend;
    Addfriend_windows window;

    Addfriend_listener(Addfriend a, Addfriend_windows w) {
        addfriend = a;
        window = w;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == window.jb2) {
            addfriend.addmassagesend();
        }


    }
}

辅助类:

package client_view;

import javax.swing.*;

public class JLabelclass extends JLabel {
    public JLabel jla;
    public String ID;
    public String hostname;
    public String Name;
    public JLabelclass(JLabel la,String id,String hname,String fname )
    {
        hostname=hname;
        jla=la;
        ID=id;
        Name=fname;
    }
}

 程序后台代码:存放于client_model包中。

登录界面后台:

package client_model;
import common.*;
import client_view.*;
import javax.swing.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Collection;

//登录界面后台 检查账号,密码;
public class Clientlogin extends JFrame {

    Client_link loginlink;
    Login window;
     public Clientlogin(Login wd) {
         loginlink=new Client_link();
         window =wd;
    }
    public  void check_login(){
         User user=new User();
         user.setType("0");
         user.setUserid(window.P1_jte1.getText());
         user.setPassword(new String(window.P1_jPa1.getPassword()));
         System.out.println(user.getUserid()+"++++++++++++++++++");
        System.out.println("调用服务器检查函数");
         Friendslist friendslist=loginlink.sendlogintoserver(user);
         user.setUsername(friendslist.getOwername());
         System.out.println(user.getUsername());
         System.out.println(friendslist.getFriends().size());
         if(friendslist.getLoginsign().equals("1")) {
             try {
                 ObjectInputStream inobj = new ObjectInputStream(loginlink.s.getInputStream());
                 Online online =null;
                 online=(Online) inobj.readObject();
                     System.out.println("收到");
                     Collection Values = online.onlinelist.values();  //获取Map集合的value集合
                     for(Object object:Values){
                          String olf=(String) object;
                        System.out.println(olf);
                     }
                     System.out.println("我是"+friendslist.getOwner()+"我登录了");
                 window.dispose();
                 loginlink.start();
                     Friend_list friend_list=new Friend_list( user,loginlink,friendslist,online);
             }catch (Exception e)
             {
                 e.printStackTrace();
             }
         }
        if(friendslist.getLoginsign().equals("0")){
            loginlink=new Client_link();
            JOptionPane.showMessageDialog(window,"                 密码错误","提示",JOptionPane.WARNING_MESSAGE);
        }
    }
    public  Friendslist Register(User u){
        User user=u;
        System.out.println(user.getUserid()+"调用注册");
        System.out.println("调用服务器检查函数");
        Friendslist friendslist=loginlink.sendlogintoserver(user);
        return friendslist;
    }
}

账号注册后台:

package client_model;

import client_view.*;
import common.*;

import javax.swing.*;

public class Register {
    Register_window window;
    User u;
    Clientlogin login;

    public Register(Clientlogin l) {
        login = l;
        window = new Register_window(this);
    }

    public void Registersend() {
        u = new User();
        u.setType("1");
        u.setUsername(window.username.getText());
        u.setUserid(window.id.getText());
        u.setPassword(new String(window.password.getPassword()));
        System.out.println("用户注册生成");
        Friendslist friendslist = login.Register(u);
        if (friendslist.getLoginsign().equals("1")) {
            System.out.println("注册成功");
            login.loginlink = new Client_link();
            window.dispose();
            JOptionPane.showMessageDialog(login.window, "            注册成功", "提示", JOptionPane.WARNING_MESSAGE);
        }
        if (friendslist.getLoginsign().equals("0")) {
            System.out.println("注册失败");
            login.loginlink = new Client_link();
            JOptionPane.showMessageDialog(window, "            该账号已被注册", "提示", JOptionPane.WARNING_MESSAGE);
        }

    }

}

好友列表后台:

package client_model;
import client_view.*;
import common.*;

public class Friend_list {
    Friend_list_window window;
    Client_link server;
    User user;
    Friendslist flist;
    Online onlf;
  public   Friend_list(User u,Client_link link,Friendslist f,Online olf)
    {
        user=u;
        flist=f;
        this.server=link;
        onlf=olf;
        window=new Friend_list_window(u.getUserid(),u.getUsername(),this,flist,server,onlf);
        server.setfriend_list(window);
    }

    
}

聊天窗口后台:

package client_model;
import client_view.Chat_window;
import common.*;

import java.text.SimpleDateFormat;
import java.util.Date;

//聊天界面后台
public class Client_Chat{
    Chat_window window;
    Client_link server;
   public Client_Chat(Chat_window wd,Client_link s)
    {
        server=s;
        this.window=wd;
    }
    public void sendmassage(){
       massage m=new massage();
       m.setType("1");
       m.setSender(window.OwnerId);
       m.setGetter(window.friendID);
       m.setTextmassage(window.jt2.getText());
                     Date NowDate = new Date();
                     SimpleDateFormat timestyle =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                     String time = timestyle.format(NowDate);
       m.setSendtime(time);
       window.jt2.setText("");
       window.jt1.append(window.hostname+" ("+m.getSendtime()+"):\r\n"+m.getTextmassage()+"\r\n");
       server.sendmassage(m);
   }
   public void showmassage(massage M, String name)
   {
       window.jt1.append(name+" ("+M.getSendtime()+"):\r\n"+M.getTextmassage()+"\r\n");
   }
}

好友添加后台:

package client_model;
import client_view.*;
import common.massage;
public class Addfriend {
Friend_list list;
public  Addfriend_windows window;
massage m;
    public Addfriend(Friend_list fl)
    {
        list=fl;
        window=new Addfriend_windows(this);
    }

    public void addmassagesend()
    {
        m=new massage();
        m.setType("3");
        m.setSender(list.user.getUserid());
        m.setGetter(window.idinput.getText());
        m.setSendername(list.window.Username);
        list.server.addfriend(m);
    }


}

客户端与服务器通讯类:

package client_model;

import java.io.*;
import java.net.*;

import client_view.Chat_window;
import client_view.Friend_list_window;
import client_view.JLabelclass;
import common.Friendslist;
import common.*;

import javax.swing.*;

//客户端后台网络连接
public class Client_link extends Thread {
    Socket s;
    ObjectOutputStream outobj;
    ObjectInputStream inobj;
    Friend_list_window flw;

    Client_link() {
        flw = null;
        try {
            s = new Socket("127.0.0.1", 1235);
            System.out.println("服务器连接成功");
            outobj = new ObjectOutputStream(s.getOutputStream());
            System.out.println("传输建立");
            inobj = new ObjectInputStream(s.getInputStream());
            System.out.println("传输建立");
        } catch (Exception e) {
            System.out.println("连接失败");
        }
    }

    public void setfriend_list(Friend_list_window fw) {

        flw = fw;
        System.out.println(flw.getTitle());

    }

    public Friendslist sendlogintoserver(Object userlogin) {
        Friendslist flist = null;
        try {
            outobj.writeObject(userlogin);
            System.out.println("登录发送");
            flist = (Friendslist) inobj.readObject();
            System.out.println("登录成功接收");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("传输断开");
        }
        return flist;
    }

    public void sendmassage(massage textmassage) {
        try {
            outobj.writeObject(textmassage);
            System.out.println("消息发送");
        } catch (Exception e) {
            System.out.println("传输断开");
        }

    }

    public void addfriend(Object addfriendmassage) {
        try {
            outobj.writeObject(addfriendmassage);
            System.out.println("加好友请求发送");
        } catch (Exception e) {
            System.out.println("传输断开");
        }

    }

    public void deletfriend(massage m) {
        try {
            outobj.writeObject(m);
            System.out.println("删除好友");
        } catch (Exception e) {
            System.out.println("传输断开");
        }
    }

    public massage receive() {
        massage M = null;
        try {
            inobj = new ObjectInputStream(s.getInputStream());
            M = (massage) inobj.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (M.gettype().equals("1")) {
            for (int i = 0; i < flw.jlac.length; i++) {
                if (M.getSender().equals(flw.jlac[i].ID)) {
                    System.out.println("收到");
                    flw.chatWindow[i].Clientchat.showmassage(M, flw.jlac[i].jla.getText());
                    flw.chatWindow[i].setVisible(true);
                    break;
                }
            }
        }
        if (M.gettype().equals("3")) {
            if (M.getSender().equals(flw.ID)) {
                System.out.println("加好友成功 发送者是我自己");
                flw.jla = (JLabel[]) resizeArray(flw.jla, flw.jla.length + 1);
                flw.jla[flw.jla.length - 1] = new JLabel(M.getFriendname(), new ImageIcon("image/头像.png"), JLabel.LEFT);
                flw.jla[flw.jla.length - 1].addMouseListener(flw.listener);
                flw.jlac = (JLabelclass[]) resizeArray(flw.jlac, flw.jlac.length + 1);
                flw.jlac[flw.jlac.length - 1] = new JLabelclass(flw.jla[flw.jla.length - 1], M.getGetter(), flw.ID, M.getFriendname());
                flw.chatWindow = (Chat_window[]) resizeArray(flw.chatWindow, flw.chatWindow.length + 1);
                flw.chatWindow[flw.chatWindow.length - 1] = new Chat_window(M.getFriendname(), M.getGetter(), M.getSender(), this, flw.Username);
                if (M.isOnline()) {
                    flw.jla[flw.jla.length - 1].setText(M.getFriendname() + " (在线)");
                    flw.chatWindow[flw.chatWindow.length - 1].setTitle(M.getFriendname() + " (在线)");
                }
                flw.jp1_1.add(flw.jla[flw.jla.length - 1]);
                flw.jp1_1.validate();
                JOptionPane.showMessageDialog(flw.addfriend.window, "            添加成功", "提示", JOptionPane.WARNING_MESSAGE);
                flw.addfriend.window.setVisible(false);
            } else {
                System.out.println("加好友成功 发送者不是我自己 是" + M.getSendername());
                flw.jla = (JLabel[]) resizeArray(flw.jla, flw.jla.length + 1);
                flw.jla[flw.jla.length - 1] = new JLabel(M.getSendername() + " 111(在线)", new ImageIcon("image/头像.png"), JLabel.LEFT);
                flw.jla[flw.jla.length - 1].addMouseListener(flw.listener);
                flw.jlac = (JLabelclass[]) resizeArray(flw.jlac, flw.jlac.length + 1);
                flw.jlac[flw.jlac.length - 1] = new JLabelclass(flw.jla[flw.jla.length - 1], M.getSender(), flw.Username, M.getSendername());
                flw.chatWindow = (Chat_window[]) resizeArray(flw.chatWindow, flw.chatWindow.length + 1);
                flw.chatWindow[flw.chatWindow.length - 1] = new Chat_window(M.getSendername(), M.getSender(), M.getGetter(), this, flw.Username);
                if (M.isOnline()) {
                    flw.jla[flw.jla.length - 1].setText(M.getSendername() + " (在线)");
                    flw.chatWindow[flw.chatWindow.length - 1].setTitle(M.getSendername() + " (在线)");
                }
                flw.jp1_1.add(flw.jla[flw.jla.length - 1]);
                flw.jp1_1.validate();
            }
        }
        if (M.gettype().equals("0")) {
            System.out.println("好友添加失败");
            JOptionPane.showMessageDialog(flw.addfriend.window, "                 账号不存在", "提示", JOptionPane.WARNING_MESSAGE);
        }
        if (M.gettype().equals("4")) {
            System.out.println("删除成功");
            JOptionPane.showMessageDialog(flw, "                 删除成功", "提示", JOptionPane.WARNING_MESSAGE);

        }
        if (M.gettype().equals("5")) {
            System.out.println(M.getSender());
            for (int i = 0; i < flw.jlac.length; i++) {
                if (M.getSender().equals(flw.jlac[i].ID)) {
                    System.out.println("有人上线了");
                    System.out.println(flw.jlac[i].jla.getText() + "上线");
                    String title = flw.jla[i].getText() + " (在线)";
                    flw.jla[i].setText(title);
                    flw.chatWindow[i].setTitle(title);
                    break;
                }
            }
        }
        if (M.getType().equals("6")) {
            System.out.println(M.getSender());
            for (int i = 0; i < flw.jlac.length; i++) {
                if (M.getSender().equals(flw.jlac[i].ID)) {
                    System.out.println("有人下线了");
                    System.out.println(flw.jlac[i].jla.getText() + "下线");
                    String title = flw.jlac[i].Name;
                    flw.jla[i].setText(title);
                    flw.chatWindow[i].setTitle(title);
                    break;
                }
            }
        }
        return M;
    }

    public void run() {
        while (true) {
            System.out.println("等待接收");
            receive();
            System.out.println("成功接收信息");
        }
    }

    private static Object resizeArray(Object oldArray, int newSize) {
        int oldSize = java.lang.reflect.Array.getLength(oldArray);
        Class elementType = oldArray.getClass().getComponentType();
        Object newArray = java.lang.reflect.Array.newInstance(elementType,
                newSize);
        int preserveLength = Math.min(oldSize, newSize);
        if (preserveLength > 0)
            System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
        return newArray;
    }

}


 

服务器代码:存放于server_model包中;

服务器主程序:

package server_model;

import common.Friendslist;
import common.User;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class myserver {
    File hashmapfile;
    FileInputStream fin;
    FileOutputStream fout;
    ObjectInputStream fobjin;
    ObjectOutputStream fobjout;

    public static void main(String args[]) {
        myserver server = new myserver();
    }

    public myserver() {
//文件准备
        hashmapfile = new File("userdata.obj");
        System.out.println(hashmapfile.isHidden());
        System.out.println(hashmapfile.getAbsolutePath());
        try {
            fin = new FileInputStream(hashmapfile);
            fobjin = new ObjectInputStream(fin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("从文件读取哈希表");
        try {
            MassageUser.userhashmap = (HashMap<String, User>) fobjin.readObject();//读取总用户数
            System.out.println("哈希表读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        ServerSocket s = null;//服务器
        try {
            s = new ServerSocket(1235);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                Socket c = s.accept();//等待连接
                System.out.println("连接成功");
                //接收信息
                ObjectInputStream objin = new ObjectInputStream(c.getInputStream());
                System.out.println("传输建立");
                ObjectOutputStream objout = new ObjectOutputStream(c.getOutputStream());
                common.User u = (common.User) objin.readObject();
                System.out.println(u.getUserid());
                System.out.println(new String(u.getPassword()));
                System.out.println(u.getType());
                if (u.getType().equals("0")) {
                    System.out.println("进入登录");//登录操作
                    String pw = MassageUser.getUser(u.getUserid()).getPassword();
                    System.out.println(pw);
                    String id = MassageUser.getUser(u.getUserid()).getUserid();
                    if (u.getPassword().equals(pw) && u.getUserid().equals(id)) {//验证账号密码
                        File listfile = new File(u.getUserid() + ".obj");
                        System.out.println(listfile.getAbsolutePath());
                        try {
                            FileInputStream flin = new FileInputStream(listfile);
                            ObjectInputStream flobjin = new ObjectInputStream(flin);
                            Friendslist flist = (Friendslist) flobjin.readObject(); //读取发送好友列表
                            System.out.println(flist.getOwername() + "好友列表人数");
                            System.out.println(flist.getFriends().size());
                            objout.writeObject(flist);
                            flobjin.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        UserThread sc = new UserThread(c, objin, objout, u.getUserid());
                        System.out.println("信息正确");
                        ManageclientThread.addClientThread(u.getUserid(), sc);
                        System.out.println("进程哈希表个数" + ManageclientThread.hm.size());
                        //启动线程
                        sc.start();
                        //登录成功 单开线程
                    } else {
                        Friendslist flist = new Friendslist(null);
                        flist.setLoginsign("0");
                        objout.writeObject(flist);
                    }

                }
                if (u.getType().equals("1")) {      //注册账户
        /*   try {
               MassageUser.userhashmap = (HashMap<String, User>) fobjin.readObject();//读取总用户数
               System.out.println("哈希表读取成功");
           }catch (Exception e)
           {
               e.printStackTrace();
           }*/
                    System.out.println("注册用户是否已经存在" + MassageUser.userhashmap.containsKey(u.getUserid()));

                    if (MassageUser.userhashmap.containsKey(u.getUserid())) {
                        Friendslist flist = new Friendslist(u.getUserid());
                        flist.setLoginsign("0");
                        objout.writeObject(flist);
                        System.out.println("注册失败");
                    }
                    if (!MassageUser.userhashmap.containsKey(u.getUserid())) {
                        MassageUser.addUser(u.getUserid(), u);
                        System.out.println(u.getUsername());
                        System.out.println("注册成功");
                        Friendslist flist = new Friendslist(u.getUserid());
                        flist.setLoginsign("1");
                        objout.writeObject(flist);
                        try {
                            fout = new FileOutputStream(hashmapfile);
                            fobjout = new ObjectOutputStream(fout);
                            fobjout.writeObject(MassageUser.userhashmap);
                            System.out.println("哈希表写入文件");

                            File friendfile = new File(u.getUserid() + ".obj");
                            System.out.println(friendfile.isHidden());
                            System.out.println(friendfile.getAbsolutePath());
                            try {
                                FileOutputStream flistout = new FileOutputStream(friendfile);
                                ObjectOutputStream flistobjout = new ObjectOutputStream(flistout);
                                Friendslist friendslist = new Friendslist(u.getUserid());
                                friendslist.setLoginsign("1");
                                friendslist.setOwername(u.getUsername());
                                flistobjout.writeObject(friendslist);
                                System.out.println("新构建好友列表存入文件");


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


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

                }


            } catch (Exception e) {
                System.out.println("服务器错误");
                e.printStackTrace();
            }
        }
    }
}

用户服务处理线程:

package server_model;

import java.io.*;
import java.net.Socket;
import java.util.Collection;

import common.*;

//服务器与客户端通讯线程
public class UserThread extends Thread {
    Socket client;
    ObjectInputStream mobjin;
    ObjectOutputStream mobjout;
    String ID;
    public UserThread(Socket c,ObjectInputStream in,ObjectOutputStream out,String id)
    {
        mobjin=in;
        mobjout=out;
        client=c;
        ID=id;
    }
    public void run()
    {
        System.out.println("开始进入线程");
        File friend_file=new File(ID+".obj");
        System.out.println(friend_file.getAbsolutePath());
        try {
            FileInputStream flist_in = new FileInputStream(friend_file);
            ObjectInputStream flistobj_in = new ObjectInputStream(flist_in);
            Friendslist friends_list = (Friendslist) flistobj_in.readObject();
            System.out.println("成功读取好友列表");
            Online onlinelist=new Online();
            Collection Values = friends_list.getFriends().values();  //获取Map集合的value集合
            for(Object object:Values){
                Friend f=(Friend) object;
                String userid=f.getId();
                if(ManageclientThread.hm.containsKey(userid))//查询在线好友
                {
                    onlinelist.onlinelist.put(userid,userid);
                }
            }
            ObjectOutputStream folobjouts=new ObjectOutputStream(client.getOutputStream());
            folobjouts.writeObject(onlinelist);
            for(Object object:Values){
                Friend f=(Friend) object;
                String userid=f.getId();
                if(ManageclientThread.hm.containsKey(userid))//查询在线好友
                {
                    UserThread getter=ManageclientThread.getClientThread(userid);
                    ObjectOutputStream onlinemaasage=new ObjectOutputStream(getter.client.getOutputStream());
                    massage m=new massage();
                    m.setType("5");
                    m.setSender(ID);
                    onlinemaasage.writeObject(m);
                    System.out.println("上线信息发送成功");
                }
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        while (true)
        {
            try {
                massage m=(massage)mobjin.readObject();
                if(m.gettype().equals("1"))//普通对话信息
                {
                    System.out.println(m.getSender()+"给"+m.getGetter()+"说"+m.getTextmassage());
                UserThread getter=ManageclientThread.getClientThread(m.getGetter());
               try{
                  mobjout=new ObjectOutputStream(getter.client.getOutputStream());
                   System.out.println("成功找出线程 接收者:"+getter.ID);
                   mobjout.writeObject(m);
                   System.out.println("成功转发");
               }catch (Exception e){
                   e.printStackTrace();
               }
                }
               if(m.gettype().equals("3"))//添加好友消息
              {
                  if(MassageUser.userhashmap.containsKey(m.getGetter())){System.out.println("添加好友请求");
                      m.setFriendname(MassageUser.getUser(m.getGetter()).getUsername());
                      System.out.println("要添加的好友是:"+m.getFriendname());
                      File friendfile=new File(m.getSender()+".obj");
                      System.out.println(friendfile.getAbsolutePath());
                      try{
                          FileInputStream flistin=new FileInputStream(friendfile);
                          ObjectInputStream flistobjin=new ObjectInputStream(flistin);
                          Friendslist friendslist=(Friendslist) flistobjin.readObject();
                          System.out.println("成功读取好友列表");

                          Collection values = friendslist.getFriends().values();  //获取Map集合的value集合
                          for(Object object:values){
                              Friend f=(Friend) object;
                              System.out.println("键值:"+f.getId());  //输出键值对象
                          }
                          System.out.println(friendslist.getOwner());
                          System.out.println(friendslist.getOwername());
                          System.out.println(friendslist.getFriends().size());
                          Friend f=new Friend();
                          f.setId(m.getGetter());
                          f.setName(m.getFriendname());
                          friendslist.addFriend(m.getGetter(),f);
                          System.out.println("存入哈希表成功");
                          System.out.println(friendslist.getFriends().size());
                          flistobjin.close();
                          FileOutputStream flistout=new FileOutputStream(friendfile);
                          ObjectOutputStream flistobjout=new ObjectOutputStream(flistout);
                          flistobjout.writeObject(friendslist);
                          flistobjout.flush();
                          flistobjout.close();
                      }catch (Exception e)
                      {
                          e.printStackTrace();
                      }

                      File friendfilegetter=new File(m.getGetter()+".obj");
                      System.out.println(friendfile.getAbsolutePath());
                      try{

                          FileInputStream flistin2=new FileInputStream(friendfilegetter);
                          ObjectInputStream flistobjin2=new ObjectInputStream(flistin2);
                          Friendslist friendslist2=(Friendslist) flistobjin2.readObject();

                          System.out.println("成功读取好友列表");
                          System.out.println(friendslist2.getOwner());
                          System.out.println(friendslist2.getOwername());
                          System.out.println(friendslist2.getFriends().size());
                          Friend f=new Friend();
                          f.setId(m.getSender());
                          f.setName(MassageUser.getUser(m.getSender()).getUsername());
                          friendslist2.addFriend(m.getSender(),f);
                          System.out.println(friendslist2.getFriends().size());
                          flistobjin2.close();
                          FileOutputStream flistout2=new FileOutputStream(friendfilegetter);
                          ObjectOutputStream flistobjout2=new ObjectOutputStream(flistout2);
                          flistobjout2.writeObject(friendslist2);
                          flistobjout2.flush();
                          flistobjout2.close();
                      }catch (Exception e)
                      {
                          e.printStackTrace();
                      }
                      try{
                          if(ManageclientThread.hm.containsKey(m.getGetter())){
                              m.setOnline(true);
                              UserThread getter=ManageclientThread.getClientThread(m.getGetter());
                              ObjectOutputStream onlinemaasage=new ObjectOutputStream(getter.client.getOutputStream());
                              onlinemaasage.writeObject(m);
                          }
                          ObjectOutputStream objouts=new ObjectOutputStream(client.getOutputStream());
                          objouts.writeObject(m);
                      }catch (Exception e){
                          e.printStackTrace();
                      }
                      System.out.println("好友请求回复发送成功");
                  }
                  else{
                           m.setType("0");
                      try{
                          ObjectOutputStream objouts=new ObjectOutputStream(client.getOutputStream());
                          objouts.writeObject(m);
                          System.out.println("好友添加失败");
                      }catch (Exception e){
                          e.printStackTrace();
                      }
                  }
              }
                if(m.gettype().equals("4"))//删除好友
                {
                    File friendfile1=new File(m.getSender()+".obj");
                    System.out.println(friendfile1.getAbsolutePath());
                    try {
                        FileInputStream flistin1 = new FileInputStream(friendfile1);
                        ObjectInputStream flistobjin1 = new ObjectInputStream(flistin1);
                        Friendslist friendslist1 = (Friendslist) flistobjin1.readObject();
                        System.out.println("成功读取好友列表");
                        friendslist1.removeFriend(m.getGetter());
                        flistobjin1.close();
                        FileOutputStream flistout1=new FileOutputStream(friendfile1);
                        ObjectOutputStream flistobjout1 = new ObjectOutputStream(flistout1);
                        flistobjout1.writeObject(friendslist1);
                        flistobjout1.flush();
                        flistobjout1.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    File friendfile2 = new File(m.getGetter() + ".obj");
                    try {
                        FileInputStream flistin2 = new FileInputStream(friendfile2);
                        ObjectInputStream flistobjin2 = new ObjectInputStream(flistin2);
                        Friendslist friendslist2 = (Friendslist) flistobjin2.readObject();
                        System.out.println("成功读取好友列表");
                        friendslist2.removeFriend(m.getSender());
                        flistobjin2.close();
                        FileOutputStream flistout2 = new FileOutputStream(friendfile2);
                        ObjectOutputStream flistobjout2 = new ObjectOutputStream(flistout2);
                        flistobjout2.writeObject(friendslist2);
                        flistobjout2.flush();
                        flistobjout2.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        ObjectOutputStream objouts = new ObjectOutputStream(client.getOutputStream());
                        objouts.writeObject(m);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {


                File friend_file_ = new File(ID + ".obj");
                System.out.println(friend_file_.getAbsolutePath());
                try {
                    FileInputStream flist_in = new FileInputStream(friend_file_);
                    ObjectInputStream flistobj_in = new ObjectInputStream(flist_in);
                    Friendslist friends_list = (Friendslist) flistobj_in.readObject();
                    System.out.println("成功读取好友列表");
                    Online onlinelist = new Online();
                    Collection Values = friends_list.getFriends().values();  //获取Map集合的value集合
                    for (Object object : Values) {
                        Friend f = (Friend) object;
                        String userid = f.getId();
                        if (ManageclientThread.hm.containsKey(userid))//查询在线好友
                        {
                            UserThread getter = ManageclientThread.getClientThread(userid);
                            ObjectOutputStream onlinemaasage = new ObjectOutputStream(getter.client.getOutputStream());
                            massage m = new massage();
                            m.setType("6");
                            m.setSender(ID);
                            onlinemaasage.writeObject(m);
                            System.out.println("下线信息发送成功");
                        }
                    }
                } catch (Exception x) {

                    x.printStackTrace();
                }


                System.out.println("线程错误");
                ManageclientThread.hm.remove(ID);
                System.out.println("进程哈希表个数" + ManageclientThread.hm.size());
                break;
            }
        }
    }
}

当前已注册用户:

package server_model;

import java.util.HashMap;
import common.*;
public class MassageUser {
    public static HashMap userhashmap=new HashMap<String, User>();
    public static void addUser(String ID, common.User u)
    {

        userhashmap.put(ID,u);
        System.out.println("用户成功存入哈希表");
    }
    public static User getUser(String ID)
    {
        return (User)userhashmap.get(ID);
    }


}

当前在线用户:

package server_model;

import java.util.HashMap;

public class ManageclientThread {
    public static HashMap hm=new HashMap<String, UserThread>();
    public static void addClientThread(String ID, UserThread ct)
    {

        hm.put(ID,ct);
        System.out.println("线程成功存入哈希表");
    }
    public static UserThread getClientThread(String ID)
    {
        return (UserThread)hm.get(ID);
    }
    public static void removeClientThread(String ID)
    {
        hm.remove(ID);
    }
}

服务器与客户端共有类:用于实现信息封装方便对象通过网络传输。存放于服务器项目与客户端项目的common包中。

1.好友类

package common;

public class Friend implements java.io.Serializable{
   private String id;
   private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

好友列表类:

package common;

import java.util.HashMap;

public class Friendslist implements java.io.Serializable {

    private String loginsign;
    private String owner;
    private HashMap friends;
    private String owername;

    public Friendslist(String id) {
        friends = new HashMap<String, Friend>();
        owner = id;
    }

    public void addFriend(String ID, Friend f) {

        friends.put(ID, f);
        System.out.println("好友成功存入哈希表");
    }

    public void removeFriend(String id) {
        friends.remove(id);
    }

    public HashMap getFriends() {
        return friends;
    }

    public String getOwner() {
        return owner;
    }

    public String getLoginsign() {
        return loginsign;
    }

    public void setLoginsign(String loginsign) {
        this.loginsign = loginsign;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getOwername() {
        return owername;
    }

    public void setOwername(String owername) {
        this.owername = owername;
    }
}

 消息类:

package common;

public class massage implements java.io.Serializable {
    private String type;
    private String sender;
    private String getter;
    private String textmassage;
    private String friendname;
    private String sendername;
    private boolean geteronline = false;
    private String sendtime;

    public String getSendername() {
        return sendername;
    }

    public void setSendername(String sendername) {
        this.sendername = sendername;
    }

    public boolean isOnline() {
        return geteronline;
    }

    public void setOnline(boolean online) {
        this.geteronline = online;
    }

    public String getType() {
        return type;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getGetter() {
        return getter;
    }

    public void setGetter(String getter) {
        this.getter = getter;
    }

    public String getTextmassage() {
        return textmassage;
    }

    public void setTextmassage(String textmassage) {
        this.textmassage = textmassage;
    }

    public String getSendtime() {
        return sendtime;
    }

    public void setSendtime(String sendtime) {
        this.sendtime = sendtime;
    }

    public void setType(String s) {

        this.type = s;
    }

    public String gettype() {
        return type;
    }

    public String getFriendname() {
        return friendname;
    }

    public void setFriendname(String friendname) {
        this.friendname = friendname;
    }
}

用户登录验证类:

package common;
public class User implements java.io.Serializable {
    private String userid;
    private String password;
    private String username;
private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserid() {
        return userid;
    }

    public String getPassword() {
        return password;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

好友在线提醒类:

package common;

import java.util.HashMap;

public class Online implements java.io.Serializable{
    public HashMap onlinelist;
    public Online() {
       onlinelist=new HashMap<String,String>();
    }
    public  void addFriend(String id, String ID )
    {
        onlinelist.put(ID,id);
    }

    public HashMap getOnlinelist() {
        return onlinelist;
    }
}

本项目中将服务器与客户端分成两个项目来进行编写。

这篇关于2021-06-14:java聊天软件编写的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!