0
点赞
收藏
分享

微信扫一扫

Java练习项目——在线聊天室

Java练习项目——在线聊天室

话不多说,先上源码:

server端:

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

public class ChatServer {

    boolean stated = false;
    ServerSocket ss = null;
    //创建集合,存储子线程
    List<Client> clients = new ArrayList<>();

    public static void main(String[] args){
        new ChatServer().start();
    }

    public void start() {
        try {
            ss = new ServerSocket(8888);
            stated = true;
        }catch (BindException e) {
            System.out.println("running ...");
            System.exit(0);
        }catch (IOException e){
            e.printStackTrace();
        }       
        try {
            //stated = true;
            while (stated) {
                Socket s = ss.accept();
                Client c = new Client(s);
System.out.println("a client connecied!");
                new Thread(c).start();
                clients.add(c);
                //dis.close();
            }
        }catch (IOException e){
            e.printStackTrace();
            //System.out.println("closed!");
        }finally {
            try {
                ss.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }

    class Client implements Runnable {
        private Socket s;
        private DataInputStream dis = null;
        private boolean bConnected = false;
        private DataOutputStream dos = null;

        public Client(Socket s) {
            this.s = s;
            try {
                dis = new DataInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());
                bConnected = true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void send(String str) {
            try {
                dos.writeUTF(str);
            } catch (IOException e) {
                clients.remove(this);
                System.out.println("对方退出了,list去除!");
            }
        }

        public void run() {
            try {
                while(bConnected) {
                    String str = dis.readUTF();
System.out.println(str);
                    //将接受的数据发送给客户端
                    for (int i=0;i<clients.size();i++) {
                        Client c = clients.get(i);
                        c.send(str);
                    }
                }
            } catch (EOFException e) {
                System.out.println("Client closed!");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(dis != null) dis.close();
                    if(dos != null) dos.close();
                    if(s != null) s.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

}

client端:

//导入Java包
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient extends Frame{

    boolean bConnected = false;
    //创建成员变量
    DataOutputStream dos = null;
    DataInputStream dis = null;
    //创建socket成员变量
    Socket s = null;
    //TextField单行文本框
    TextField tfText = new TextField();
    // TextArea多行文本框
    TextArea taContent = new TextArea();
    //成员变量
    Thread tRecv = new Thread(new RecvThread());

    public static void main(String[] args) {
        //创建对象并调用方法
        ChatClient q = new ChatClient();
        q.launchFrame();
    }

    //创建窗体方法
    public void launchFrame() {
        //调整窗口大小
        setLocation(400,300);
        this.setSize(300,300);
        //在窗口的北(上)方,南(下)方添加文本框
        add(tfText, BorderLayout.SOUTH);
        add(taContent, BorderLayout.NORTH);
        //隐藏多余窗口区域
        pack();
        this.addWindowListener(new WindowAdapter(){
            //重写WindowAdapter()类的windowClosing方法
            //实现点击关闭终止程序
            @Override
            public void windowClosing(WindowEvent e) {
                disconnect();
                System.exit(0);
            }
        });
        //调用Button类中的addActionListener方法
        tfText.addActionListener(new TextListener());
        setVisible(true);
        connect();
        tRecv.start();
    }

    //创建客户端连接服务器方法
    public void connect() {
        //使用try/catch语句防止错误异常抛出
        try {
            s = new Socket("127.0.0.1",8888);
            dis = new DataInputStream(s.getInputStream());
            dos = new DataOutputStream(s.getOutputStream());
System.out.println("connected!");
            bConnected = true;
        } catch (UnknownHostException e) {
            //找不到主机异常
            e.printStackTrace();
        } catch (IOException e) {
            //输入错误,连接错误
            //e.printStackTrace();
            System.out.println("输入错误,连接失败");
        }

    }

    //添加清理方法,关闭套接字时将内存等清理
    public void disconnect() {
        try {
            dos.close();
            dis.close();
            s.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

    //创建继承于ActionListener的类
    private class TextListener implements ActionListener{

        //重写actionPerformed方法
        public void actionPerformed(ActionEvent e) {
            String str = tfText.getText().trim();
            //taContent.setText(str);
            tfText.setText("");
            try {
                dos.writeUTF(str);
                dos.flush();
                //dos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    private class RecvThread implements Runnable {

        public void run() {
            try {
                while (bConnected) {
                    String str = dis.readUTF();
                    //System.out.println(str);
                    taContent.setText(taContent.getText() + str + "\n");
                }
            }catch (SocketException e) {
                System.out.println("退出了,bye!");
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

PS:该练习可实现类似在线聊天系统的小功能,本人的第一个的练习,还有很多不足之处,请各位大佬指教。

举报

相关推荐

0 条评论