Java网络编程-简易聊天室源码分享

更新了简易聊天室程序,新增滚动条功能,修改窗口名称并添加注释。此程序包括服务器端和客户端,支持多用户实时聊天,显示发送与接收消息的时间戳。

2022年6月8日更新,版本 v1.1
更新内容:
(1)应广大朋友要求,增加了滚动条
(2)同时修改了窗口的名称
(3)添加了一些注释

后续更新内容:考虑加一个群聊,目前好像是不行的,多开客户端会发生错误
new

代码放在下面了
同样需要先打开服务端,再打开客户端!

服务器端

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务器端窗口,先运行这个
 */
public class GUIServer {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("JAVA版简易聊天室-服务器端");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);
        // 发送按钮
        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);
        // 下侧聊天输入框
        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);
        // 上侧聊天内容
        JTextArea ta = new JTextArea();
        // 设置为不可编辑
        ta.setEditable(false);
        // 文字比控件的宽度还长时会自动换行
        ta.setLineWrap(true);
        // 在单词边界换行,而不是粗暴的直接在字符边界换行
        ta.setWrapStyleWord(true);
        // 增加滚动条
        JScrollPane sp = new JScrollPane(ta);
        sp.setBounds(10, 10, 360, 200);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        f.add(sp);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            // 设置服务器的端口为8888
            ServerSocket ss = new ServerSocket(8888);
            // 设置为接收模式
            Socket s = ss.accept();
            // 发送按钮的点击事件
            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    ta.setCaretPosition(ta.getText().length());
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                            ta.setCaretPosition(ta.getText().length());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

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


    }

}


客户机端

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 客户端程序
 */
public class GUIClient {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("JAVA版简易聊天室-客户机端");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);
        // 发送按钮
        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);
        // 下侧聊天输入框
        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);
        // 上侧聊天内容
        JTextArea ta = new JTextArea();
        // 设置为不可编辑
        ta.setEditable(false);
        // 文字比控件的宽度还长时会自动换行
        ta.setLineWrap(true);
        // 在单词边界换行,而不是粗暴的直接在字符边界换行
        ta.setWrapStyleWord(true);
        // 增加滚动条
        JScrollPane sp = new JScrollPane(ta);
        sp.setBounds(10, 10, 360, 200);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        f.add(sp);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            // 设置连接服务器的地址为本机,端口为8888
            Socket s = new Socket("127.0.0.1", 8888);

            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

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

}



原贴

简易的聊天小程序,在使用时请先开启服务器程序,再运行客户端程序
在这里插入图片描述

package socket;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务器端窗口,先运行这个
 */
public class GUIServer {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("服务器");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);

        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);

        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);

        JTextArea ta = new JTextArea();
        ta.setBounds(10, 10, 360, 200);
        f.add(ta);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            ServerSocket ss = new ServerSocket(8888);
            Socket s = ss.accept();

            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    ta.setCaretPosition(ta.getText().length());
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                            ta.setCaretPosition(ta.getText().length());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();


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


    }

}

package socket;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 客户端程序
 */
public class GUIClient {

    public static void main(String[] args) {
        // 创建窗体
        JFrame f = new JFrame("客户端");
        f.setLayout(null);
        // 设置大小和位置
        f.setSize(400, 300);
        f.setLocation(100, 200);

        JButton b = new JButton("发送");
        b.setBounds(290, 220, 80, 30);
        f.add(b);

        JTextField tf = new JTextField();
        tf.setBounds(10, 220, 260, 30);
        f.add(tf);

        JTextArea ta = new JTextArea();
        ta.setBounds(10, 10, 360, 200);
        f.add(ta);

        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);

        try {
            Socket s = new Socket("127.0.0.1", 8888);

            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取输入文本
                    String text = tf.getText();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                    String now = sdf.format(date);
                    ta.append(now +"\r\n我:" + text + "\r\n");
                    // 设置输入框为空
                    tf.setText("");
                    // 发送信息
                    try {
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(text);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            // 接收信息线程
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            // 获取其他用户的输入
                            DataInputStream dis = new DataInputStream(s.getInputStream());
                            String text = dis.readUTF();
                            String ip = s.getInetAddress().getHostAddress();
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss");
                            String now = sdf.format(date);
                            // 添加到页面上
                            ta.append(now + "\r\n" + ip + ":" + text + "\r\n");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();


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

}

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值