JAVA聊天室代码

聊天室界面:
这里写图片描述

源码:

public class ClientFrame extends Frame {

    private TextField textFieldContent = new TextField();
    private TextArea textAreaContent = new TextArea();
    private Socket socket = null;
    private OutputStream out = null;
    private DataOutputStream dos = null;
    private InputStream in = null;
    private DataInputStream dis = null;
    private boolean flag = false;

    /**
     * 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:19:51 功能:启动客户端程序
     * 
     * @param args
     */
    public static void main(String[] args) {
        new ClientFrame().init();
    }

    /**
     * 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:20:43 功能:对窗口进行初始化
     */
    private void init() {
        this.setSize(300, 300);
        setLocation(250, 150);
        setVisible(true);
        setTitle("WeChatRoom");

        // 添加控件
        this.add(textAreaContent);
        this.add(textFieldContent, BorderLayout.SOUTH);
        textAreaContent.setFocusable(false);
        pack();

        // 关闭事件
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.out.println("用户试图关闭窗口");
                disconnect();
                System.exit(0);
            }

        });
        // textFieldContent添加回车事件
        textFieldContent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onClickEnter();
            }
        });

        // 建立连接
        connect();
        new Thread(new ReciveMessage()).start();
    }

    private class ReciveMessage implements Runnable {
        @Override
        public void run() {
            flag = true;
            try {
                while (flag) {
                    String message = dis.readUTF();
                    textAreaContent.append(message + "\n");
                }
            } catch (EOFException e) {
                flag = false;
                System.out.println("客户端已关闭");
                // e.printStackTrace();
            } catch (SocketException e) {
                flag = false;
                System.out.println("客户端已关闭");
                // e.printStackTrace();
            } catch (IOException e) {
                flag = false;
                System.out.println("接受消息失败");
                e.printStackTrace();
            }
        }

    }

    /**
     * 功能:当点击回车时出发的事件 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午9:49:30
     */
    private void onClickEnter() {
        String message = textFieldContent.getText().trim();
        if (message != null && !message.equals("")) {
            String time = new SimpleDateFormat("h:m:s").format(new Date());
            textAreaContent.append(time + "\n" + message + "\n");
            textFieldContent.setText("");
            sendMessageToServer(message);
        }
    }

    /**
     * 功能:给服务器发送消息 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:13:48
     * 
     * @param message
     */
    private void sendMessageToServer(String message) {
        try {
            dos.writeUTF(message);
            dos.flush();
        } catch (IOException e) {
            System.out.println("发送消息失败");
            e.printStackTrace();
        }
    }

    /**
     * 功能:申请socket链接 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:00:38
     */
    private void connect() {
        try {
            socket = new Socket("localhost", 8888);
            out = socket.getOutputStream();
            dos = new DataOutputStream(out);
            in = socket.getInputStream();
            dis = new DataInputStream(in);
        } catch (UnknownHostException e) {
            System.out.println("申请链接失败");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("申请链接失败");
            e.printStackTrace();
        }
    }

    /**
     * 功能:关闭流和链接 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:01:32
     */
    private void disconnect() {
        flag = false;
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                System.out.println("dos关闭失败");
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                System.out.println("dos关闭失败");
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("socket关闭失败");
                e.printStackTrace();
            }
            ;
        }
    }

}
package com.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {

    private List<Client> clients = new ArrayList<>();

    /**
     * 功能:启动ChatSever 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:26:41
     * 
     * @param args
     */
    public static void main(String[] args) {
        new ChatServer().init();
    }

    /**
     * 功能:对chatserver初始化 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午10:27:09
     */
    private void init() {
        System.out.println("服务器已开启");
        // BindException

        ServerSocket ss = null;
        Socket socket = null;
        try {
            ss = new ServerSocket(8888);
        } catch (BindException e) {
            System.out.println("端口已被占用");
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            Client client = null;
            while (true) {
                socket = ss.accept();
                System.out.println("客户驾到");
                client = new Client(socket);
                clients.add(client);
                new Thread(client).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class Client implements Runnable {
        private Socket socket = null;
        InputStream in = null;
        DataInputStream din = null;
        OutputStream out = null;
        DataOutputStream dos = null;
        boolean flag = true;

        public Client(Socket socket) {
            this.socket = socket;
            try {
                in = socket.getInputStream();
                din = new DataInputStream(in);
            } catch (IOException e) {
                System.out.println("接受消息失败");
                e.printStackTrace();
            }

        }

        public void run() {

            String message;
            try {
                while (flag) {
                    message = din.readUTF();
                    // System.out.println("客户说:" + message);
                    forwordToAllClients(message);
                }
            } catch (SocketException e) {
                flag = false;
                System.out.println("客户下线");
                clients.remove(this);
                // e.printStackTrace();
            } catch (EOFException e) {
                flag = false;
                System.out.println("客户下线");
                clients.remove(this);
                // e.printStackTrace();
            } catch (IOException e) {
                flag = false;
                System.out.println("接受消息失败");
                clients.remove(this);
                e.printStackTrace();
            }

            if (din != null) {
                try {
                    din.close();
                } catch (IOException e) {
                    System.out.println("din关闭失败");
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.out.println("din关闭失败");
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("din关闭失败");
                    e.printStackTrace();
                }
            }

        }

        /**
         * 功能:转发给所有客户端 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午11:11:59
         * 
         * @param message
         * @throws IOException
         */
        private void forwordToAllClients(String message) throws IOException {
            for (Client c : clients) {
                if (c != this) {
                    out = c.socket.getOutputStream();
                    dos = new DataOutputStream(out);
                    forwordToClient(message);
                }
            }
        }

        /**
         * 功能:发送给一个客户端 学校:山东师范大学 程序员:外力_Victor 日期:2016年5月8日 上午11:16:12
         * 
         * @throws IOException
         */
        private void forwordToClient(String message) throws IOException {
            dos.writeUTF(message);
            dos.flush();
            System.out.println("转发成功!");
        }

    }
}

源码下载:http://download.csdn.net/detail/qq_24082497/9513776

  • 5
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java聊天室程序 需求分析 2.1 业务需求 1. 与聊天室成员一起聊天。 2. 可以与聊天室成员私聊。 3. 可以改变聊天内容风格。 4. 用户注册(含头像)、登录。 5. 服务器监控聊天内容。 6. 服务器过滤非法内容。 7. 服务器发送通知。 8. 服务器踢人。 9. 保存服务器日志。 10.保存用户聊天信息。 2.2 系统功能模块 2.2.1 服务器端 1.处理用户注册 2.处理用户登录 3.处理用户发送信息 4.处理用户得到信息 5.处理用户退出 2.2.2 客户端 1.用户注册界面及结果 2.用户登录界面及结果 3.用户发送信息界面及结果 4.用户得到信息界面及结果 5.用户退出界面及结果 2.3 性能需求 运行环境:Windows 9x、2000、xp、2003,Linux 必要环境:JDK 1.5 以上 硬件环境:CPU 400MHz以上,内存64MB以上 3.1.2 客户端结构 ChatClient.java 为客户端程序启动类,负责客户端的启动和退出。 Login.java 为客户端程序登录界面,负责用户帐号信息的验证与反馈。 Register.java 为客户端程序注册界面,负责用户帐号信息的注册验证与反馈。 ChatRoom.java 为客户端程序聊天室界面,负责接收、发送聊天内容与服务器端的Connection.java 亲密合作。 Windowclose 为ChatRoom.java的内部类,负责监听聊天室界面的操作,当用户退出时返回给服务器信息。 Clock.java 为客户端程序的一个小程序,实现的一个石英钟功能。 3. 2 系统实现原理 当用户聊天时,将当前用户名、聊天对象、聊天内容、聊天语气和是否私聊进行封装,然后与服务器建立Socket连接,再用对象输出流包装Socket的输出流将聊天信息对象发送给服务器端 当用户发送聊天信息时,服务端将会收到客户端用Socket传输过来的聊天信息对象,然后将其强制转换为Chat对象,并将本次用户的聊天信息对象添加到聊天对象集Message中,以供所有聊天用户访问。 接收用户的聊天信息是由多线程技术实现的,因为客户端必须时时关注更新服务器上是否有最新消息,在本程序中设定的是3秒刷新服务器一次,如果间隔时间太短将会增加客户端与服务器端的通信负担,而间隔时间长就会让人感觉没有时效性,所以经过权衡后认为3秒最佳,因为每个用户都不可能在3秒内连续发送信息。 当每次用户接收到聊天信息后将会开始分析聊天信息然后将适合自己的信息人性化地显示在聊天信息界面上。 4.1.1 问题陈述 1.接受用户注册信息并保存在一个基于文件的对象型数据库。 2.能够允许注册过的用户登陆聊天界面并可以聊天。 3.能够接受私聊信息并发送给特定的用户。 4.服务器运行在自定义的端口上#1001。 5.服务器监控用户列表和用户聊天信息(私聊除外)。 6.服务器踢人,发送通知。 7.服务器保存日志。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值