Java群聊天(Group chat)借鉴百度文库代码改编

Java群聊天代码(Group chat)

  1. Server.java(服务器)
  2. ServerThread.java(服务器线程)
  3. Client.java(客户端)
  4. ClientThread.java(客户端线程)
**文件Server.java全代码:**

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

public class Server{

    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(8888);
          Vector<Socket> person = new Vector<Socket>();
        //开启服务端口8888
        int chatNum = 0;
        //计数用户登入号
System.out.println("服务器启动成功!");
      String ip = InetAddress.getLocalHost()+"";
      String ary[] = ip.split("/");
System.out.println("把" +ary[1] +"告诉你群聊的小伙伴们,就可以开始聊天啦");
        while(true){
          //死循环用于接收用户的接入
            Socket s = ss.accept();
          //等待用户连接
            chatNum++;
          //用户数自增
            InputStream in =s.getInputStream();
            InputStreamReader inr = new InputStreamReader(in);
          //获取每个用户的输入流
            person.add(s);
          new ServerThread(in,person).start();
System.out.println(chatNum + "用户连接成功");
        }
    }
}
**文件ServerThread.java全代码**

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

public class ServerThread extends Thread{

  InputStream in;//全局变量
  Vector<Socket> person;

//方法重构
  public ServerThread(InputStream in,Vector<Socket> person){
    this.in = in;
    this.person = person;
  }

  public void run(){
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);

    while(true){
        try{
              String message = br.readLine();
System.out.println("收到消息:"+message);
          for(int i = 0;i<person.size();i++){
              Socket sock = person.get(i);
              OutputStream os = sock.getOutputStream();
              PrintWriter pw = new PrintWriter(os,true);
              pw.println(message);
          }

        } catch(IOException e){
            e.printStackTrace();
            break;
        }
    }
      System.exit(0);
  }
}

**文件Client.java全代码**

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;

public class Client extends JFrame implements ActionListener{
    JButton conBut=new JButton("连接服务器");
    JButton sendBut=new JButton("发送信息");

    JTextField servername=new JTextField(20);
    JTextField username=new JTextField(20);
    JTextField content=new JTextField(20);

    JLabel lab=new JLabel("服务器名:");
    JLabel lab1=new JLabel("大厅用户名:");
    JLabel jcb=new JLabel("所有人");

    public JTextArea ttt=new JTextArea();
    Socket sock;

    public Client() {

        JPanel p1=new JPanel();
        JPanel p2=new JPanel();
        JPanel p3=new JPanel();
        JPanel p4=new JPanel();

        p1.add(this.lab);
        p1.add(this.servername);
        p1.add(this.conBut);

        p4.add(this.lab1);
        p4.add(this.username);

        p2.add(this.jcb);
        p2.add(this.content);
        p2.add(this.sendBut);

        this.conBut.addActionListener(this);
        this.sendBut.addActionListener(this);

        p3.setLayout(new BorderLayout());
        p3.add("South",p2);
        p3.add("Center",new JScrollPane(ttt));

        this.add("North",p4);
        this.add("South",p1);
        this.add("Center",p3);

        this.setSize(550, 550);
        this.setResizable(false);
        this.setTitle("聊天大厅");
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
    }


public static void main(String[] args) {
        Client cl=new Client();
        cl.setVisible(true);
    }


    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==this.conBut){
            String fuwuqi=this.servername.getText();
            String usernametemp = username.getText();
            if(fuwuqi == null || "".equals(fuwuqi) || "".equals(usernametemp)){
                JOptionPane.showMessageDialog(null, "输入用户名、服务器名或IP地址");
            }else{
                try {
                     sock=new Socket(fuwuqi,8888);
                     DataInputStream is = new DataInputStream(sock.getInputStream());
                     new ClientThread(is,this).start();
                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                conBut.setText("连接成功");
                conBut.setEnabled(false);
        }
        }
        else{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = df.format(new Date());
System.out.println(time);
        String temp = content.getText();
            if("".equals(temp)){
                JOptionPane.showMessageDialog(null, "别不说话呀");
            }else{
            String msg= "*****"+username.getText()+"*****"+"%在"+time + "向所有人说:%" + content.getText()+"%end";
            try {
                DataOutputStream os = new DataOutputStream(sock.getOutputStream());
                PrintWriter pw=new PrintWriter(os,true);
                pw.println(msg);
                this.content.setText("");
            }catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    }

}


**文件ClientThread.java全代码**

import java.io.*;
import javax.swing.JTextArea;


public class ClientThread extends Thread {

    InputStream in;
    JTextArea ttt;

    public ClientThread(InputStream in,Client c) {

        this.in=in;
        this.ttt=c.ttt;
    }

    public void run() {
        InputStreamReader isr=new InputStreamReader(in);
        BufferedReader br=new BufferedReader(isr);
        while(true){
            try {
                String str=br.readLine();
                String shujuzu[] = str.split("%");
                if(shujuzu[3].equals("end")){
                ttt.append(shujuzu[0]+"\r\n");
                ttt.append(shujuzu[1]+"\r\n");
                ttt.append(shujuzu[2]+"\r\n"+"\r\n");
                }
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

    }

}
                **本文代码可直接编译执行**
        cmd寻找文件所在目录编译代码
        javac -encoding utf8 ServerThread.java
        javac -encoding utf8 Server.java
        javac -encoding utf8 Client.java
        javac -encoding utf8 ClientThread.java
        执行
        java Server
        java Client

        群聊功能请自行多起客户端进行测试
        由于水平限制,程序仍存在众多BUG,可评论指出,共同进步!
                感谢百度文库用户chenxueyu1028

引用自
百度文库用户chenxueyu1028

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值