简单的线程JavaSwing聊天小程序

package server;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * 服务端
 */
public class ServerHome extends JFrame implements ActionListener {
    private JLabel statusLab;//窗口上面的状态
    private JTextArea talkArea;//聊天区域
    private JTextArea sendArea;//发送信息区域
    private JButton sendBtn;//发送按钮
    private JTextArea infoArea;//侧面的信息栏
    private JScrollPane talkScroll;//聊天区域滚条


    private ServerSocket server;
    private Socket socket;
    private InputStream is;
    private OutputStream os;

    public ServerHome(){
        init();
    }

    private void init() {
        /**
         * 设置窗口的初始化
         */
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        int width = screenSize.width;
        int height = screenSize.height;
        setBounds((width-976)/2,(height-680)/2,976,680);
        Container contentPane = this.getContentPane();
        /**
         * 设置上方好友名
         */
        statusLab = new JLabel("好友:客户端");
        statusLab.setFont(new Font("宋体",Font.BOLD,20));
        statusLab.setBounds(0,0,1000,50);
        statusLab.setBackground(Color.black);
        statusLab.setForeground(Color.black);
        statusLab.setHorizontalAlignment(JLabel.CENTER);//设置水平居中
        statusLab.setVerticalAlignment(JLabel.CENTER);//设置竖直剧中
        contentPane.add(statusLab);

        /**
         * 设置聊天区域
         */
        talkArea = new JTextArea();
        talkArea.setBackground(Color.white);
        talkArea.setEnabled(false);//设置不可输入
        talkArea.setLineWrap(true);//设置可换行
        talkArea.setFont(new Font("黑体",Font.ITALIC,20));
        talkScroll = new JScrollPane(talkArea);
        talkScroll.setBounds(0,50,777,454);
        contentPane.add(talkScroll);

        /**
         * 设置发送区域
         */
        sendArea = new JTextArea();
//        sendArea.setBounds(0,510,777,100);
        sendArea.setBackground(Color.white);
        sendArea.setFont(new Font("微软雅黑",Font.BOLD,18));
        sendArea.setLineWrap(true);
        talkScroll = new JScrollPane(sendArea);
        talkScroll.setBounds(0,510,777,100);
        contentPane.add(talkScroll);

        /**
         * 发送按钮
         */
        sendBtn = new JButton("发送");
        sendBtn.setBounds(667,604,110,30);
        sendBtn.setBackground(Color.black);
        sendBtn.setForeground(Color.white);
        sendBtn.setFont(new Font("宋体",Font.BOLD,18));
        contentPane.add(sendBtn);

        /**
         * 好友信息
         */
        infoArea = new JTextArea();
        infoArea.setBounds(780,50,181,583);
        infoArea.setBackground(Color.white);
        infoArea.setText("这里是好友资料");
        infoArea.setFont(new Font("微软雅黑",Font.ITALIC,18));
        contentPane.add(infoArea);
        /**
         * 给按钮添加监听事件
         */
        sendBtn.addActionListener(this);

        /**
         * 开启多线程
         */
        new ListenThread().start();
    }


    /**
     * 该线程用网络输入流来读取客户端发来的数据
     */
    public class ListenThread extends Thread{
        @Override
        public void run() {
            try {
                //端口号为8888,最大允许1000个客户端连接
                server = new ServerSocket(8888,1000);
                //监听,等待连接,一旦有client端连接便创建socket实例.
                //然后通过socket交互数据.
                socket = server.accept();
                is = socket.getInputStream();
                os = socket.getOutputStream();

                while (true){
                    byte [] buf = new byte[1024];
                    int len = is.read(buf);

                    byte [] sbuf = new byte[len];
                    System.arraycopy(buf,0,sbuf,0,len);
                    //把字节转换为字符
                    String text = new String(sbuf);

                    talkArea.append(new Date()+"\n"+"客户端:"+text+"\n");
                    sendArea.setText("");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



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


    /**
     * 这个监听用来将发送的消息显示到聊天框上
     * 并且通过网络输出流输出到客户端
     * @param event
     */
    @Override
    public void actionPerformed(ActionEvent event) {
        if(event.getSource()==sendBtn){
            String sendInfo = sendArea.getText();
            if(!"".equals(sendInfo)&&sendInfo!=null){
                talkArea.append(new Date()+"\n"+"服务端:"+sendInfo+"\n");
                sendArea.setText("");

                try {
                    os = socket.getOutputStream();
                    byte buf [] = new byte[1024];
                    buf = sendInfo.getBytes();
                    os.write(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }
}




`package client;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * 客户端
 */
public class ClientHome extends JFrame implements ActionListener{
    private JLabel statusLab;//窗口上面的状态
    private JTextArea talkArea;//聊天区域
    private JTextArea sendArea;//发送信息区域
    private JButton sendBtn;//发送按钮
    private JTextArea infoArea;//侧面的信息栏
    private JScrollPane talkScroll;//聊天区域滚条


    private Socket socket;
    private InputStream is;
    private OutputStream os;

    public ClientHome(){
        init();
    }

    private void init() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        int width = screenSize.width;
        int height = screenSize.height;
        setBounds((width-976)/2,(height-680)/2,976,680);
        Container contentPane = this.getContentPane();
        statusLab = new JLabel("好友:服务端");
        statusLab.setFont(new Font("宋体",Font.BOLD,20));
        statusLab.setBounds(0,0,1000,50);
        statusLab.setBackground(Color.black);
        statusLab.setForeground(Color.black);
        statusLab.setHorizontalAlignment(JLabel.CENTER);//设置水平居中
        statusLab.setVerticalAlignment(JLabel.CENTER);//设置竖直剧中
        contentPane.add(statusLab);


        talkArea = new JTextArea();
        talkArea.setBackground(Color.white);
        talkArea.setEnabled(false);//设置不可输入
        talkArea.setLineWrap(true);//设置可换行
        talkArea.setFont(new Font("黑体",Font.ITALIC,20));
        talkScroll = new JScrollPane(talkArea);
        talkScroll.setBounds(0,50,777,454);
        contentPane.add(talkScroll);

        sendArea = new JTextArea();
//        sendArea.setBounds(0,510,777,100);
        sendArea.setBackground(Color.white);
        sendArea.setFont(new Font("微软雅黑",Font.BOLD,18));
        sendArea.setLineWrap(true);
        talkScroll = new JScrollPane(sendArea);
        talkScroll.setBounds(0,510,777,100);
        contentPane.add(talkScroll);


        sendBtn = new JButton("发送");
        sendBtn.setBounds(667,604,110,30);
        sendBtn.setBackground(Color.black);
        sendBtn.setForeground(Color.white);
        sendBtn.setFont(new Font("宋体",Font.BOLD,18));
        contentPane.add(sendBtn);

        infoArea = new JTextArea();
        infoArea.setBounds(780,50,181,583);
        infoArea.setBackground(Color.white);
        infoArea.setText("这里是好友资料");
        infoArea.setFont(new Font("微软雅黑",Font.ITALIC,18));
        contentPane.add(infoArea);

        sendBtn.addActionListener(this);

        new ListenThread().start();
    }

    public class ListenThread extends Thread{

        @Override
        public void run() {
            try {
                socket = new Socket("127.0.0.1",8888);
                is = socket.getInputStream();
                os = socket.getOutputStream();

                while (true){
                    byte [] buf = new byte[1024];
                    int len = is.read(buf);
                    byte [] sbuf = new byte[len];
                    System.arraycopy(buf,0,sbuf,0,len);
                    //把字节转换为字符
                    String text = new String(sbuf);

                    talkArea.append(new Date()+"\n"+"服务端:"+text+"\n");
                    sendArea.setText("");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



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


    @Override
    public void actionPerformed(ActionEvent event) {
        if(event.getSource()==sendBtn){
            String sendInfo = sendArea.getText();
            if(!"".equals(sendInfo)&&sendInfo!=null){
                talkArea.append(new Date()+"\n"+"客户端:"+sendInfo+"\n");
                sendArea.setText("");

                try {
                    os = socket.getOutputStream();
                    byte buf [] = new byte[1024];
                    buf = sendInfo.getBytes();
                    os.write(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }
}

``

你可能感兴趣的:(简单的线程JavaSwing聊天小程序)