java实现的多人聊天程序

来源:互联网 发布:如何通过ip找到域名 编辑:程序博客网 时间:2024/04/29 17:17
http://www.oschina.net/code/snippet_198455_23933
用java实现的一个简单的多人聊天程序
标签: <无>

源码与演示:源码出处

代码片段(3)[全屏查看所有代码]

1. [文件] ChatClient.java ~ 2KB     下载(209)     

001package org.dxer;
002import java.io.BufferedReader;
003import java.io.DataInputStream;
004import java.io.DataOutputStream;
005import java.io.IOException;
006import java.io.InputStreamReader;
007import java.net.Socket;
008 
009public class ChatClient {
010    private DataOutputStream output;
011    private DataInputStream input;
012    /* 服务器端口号 */
013    public static final int PORT = 10001;
014    /* 客户端名称 */
015    private String clientName;
016 
017    public ChatClient(String clientName) {
018        this.clientName = clientName;
019    }
020 
021    public static void main(String[] args) {
022        if (args.length < 1) {
023            System.err.println("Usage:\n\t" + ChatClient.class.getName()
024                    " <ClientName>");
025            System.exit(1);
026        }
027        // 连接服务器
028        new ChatClient(args[0]).connect("127.0.0.1");
029    }
030 
031    public void connect(String host) {
032        Socket socket = null;
033        try {
034            socket = new Socket(host, PORT);
035            System.out.println("Connected to server");
036            input = new DataInputStream(socket.getInputStream());
037            output = new DataOutputStream(socket.getOutputStream());
038            ReadThread readThread = new ReadThread();
039            WriteThread writeThread = new WriteThread();
040            readThread.start();
041            writeThread.start();
042 
043            readThread.join();
044            writeThread.join();
045        catch (Exception e) {
046            e.printStackTrace();
047        finally {
048            try {
049                if (input != null) {
050                    input.close();
051                }
052                if (output != null) {
053                    output.close();
054                }
055                if (socket != null) {
056                    socket.close();
057                }
058            catch (IOException e) {
059            }
060        }
061    }
062 
063    public class ReadThread extends Thread {
064 
065        public void run() {
066            String msg = null;
067            try {
068                while (true) {
069                    msg = input.readUTF();
070                    if (msg != null) {
071                        if (!msg.equals("bye")) {
072                            System.out.println(msg);
073                        else {
074                            break;
075                        }
076                    }
077                }
078            catch (Exception e) {
079                e.printStackTrace();
080            }
081        }
082    }
083 
084    public class WriteThread extends Thread {
085 
086        public void run() {
087            try {
088                BufferedReader stdIn = new BufferedReader(
089                        new InputStreamReader(System.in));
090                String message = null;
091                while (true) {
092                    System.out.print("> ");
093                    message = stdIn.readLine();
094                    output.writeUTF("[" + clientName + "]$ " + message);
095                    if (message.equals("bye")) {
096                        break;
097                    }
098                }
099            catch (Exception e) {
100                e.printStackTrace();
101            }
102        }
103    }
104 
105}

2. [文件] ChatServer.java ~ 2KB     下载(184)     

001package org.dxer;
002import java.io.DataInputStream;
003import java.io.DataOutputStream;
004import java.io.IOException;
005import java.net.ServerSocket;
006import java.net.Socket;
007import java.util.ArrayList;
008 
009public class ChatServer {
010 
011    /* 客户端列表 */
012    ArrayList<Socket> clientList = new ArrayList<Socket>();
013    /* 端口号 */
014    public static final int PORT = 10001;
015 
016    public static void main(String[] args) {
017        // 在main函数中,启动服务器
018        new ChatServer().start();
019    }
020 
021    public void start() {
022        ServerSocket server = null;
023        try {
024            server = new ServerSocket(PORT);
025            System.out.println("Server is started...");
026            Socket socket = null;
027            while ((socket = server.accept()) != null) {
028                clientList.add(socket);
029                System.out.println(socket.getInetAddress().getHostAddress()
030                        " connected to the server");
031                new WorkThread(socket).start();
032            }
033        catch (Exception e) {
034            System.out.println(e.toString());
035        finally {
036            if (server != null) {
037                try {
038                    server.close();
039                catch (IOException e) {
040                }
041            }
042        }
043    }
044 
045    public class WorkThread extends Thread {
046        private Socket socket;
047 
048        public WorkThread(Socket client) {
049            this.socket = client;
050        }
051 
052        @Override
053        public void run() {
054            DataOutputStream output = null;
055            DataInputStream input = null;
056            try {
057                String msg = null;
058                String message = null;
059                input = new DataInputStream(socket.getInputStream());
060                while (true) {
061                    msg = input.readUTF();
062                    System.out.println(msg);
063                    if (msg.trim().endsWith("]$ bye")) {
064                        System.out.println(socket.getInetAddress()
065                                .getHostAddress() + " is exited");
066                        output = new DataOutputStream(socket.getOutputStream());
067                        output.writeUTF("bye");
068                        clientList.remove(socket);
069                        break;
070                    }
071                    message = "[" + Util.getTime() + " "
072                            + Util.getClientName(msg) + "]$ "
073                            + Util.getContent(msg);
074                    for (int i = 0; i < clientList.size(); i++) {
075                        Socket s = clientList.get(i);
076                        if (s != socket) {
077                            output = new DataOutputStream(s.getOutputStream());
078                            output.writeUTF(message);
079                        }
080                    }
081                }
082            catch (Exception e) {
083                e.printStackTrace();
084            finally {
085                try {
086                    if (input != null) {
087                        input.close();
088                    }
089 
090                    if (output != null) {
091                        output.close();
092                    }
093 
094                    if (socket != null) {
095                        socket.close();
096                    }
097                catch (IOException e) {
098                }
099            }
100        }
101    }
102 
103}

3. [文件] Util.java ~ 834B     下载(172)     

01package org.dxer;
02import java.text.SimpleDateFormat;
03import java.util.Date;
04 
05public class Util {
06 
07    /**
08     * 获得当前时间
09     *
10     * @return
11     */
12    public static String getTime() {
13        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
14        return df.format(new Date()).toString();
15    }
16 
17    /**
18     * 获得client的名字
19     *
20     * @param message
21     * @return
22     */
23    public static String getClientName(String message) {
24        String name = null;
25        int len = message.indexOf("]$ ");
26        name = message.substring(1, len);
27        return name;
28    }
29 
30    /**
31     * 获得消息的正文部分
32     *
33     * @param message
34     * @return
35     */
36    public static String getContent(String message) {
37        String content = null;
38        int len = message.indexOf("]$ ");
39        content = message.substring(len + 3);
40        return content.trim();
41    }
42}
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 台式电脑放歌没有声音怎么办 微信图片上传大愎怎么办 行车记录仪内存卡丢了怎么办 投资项目失败lp的钱怎么办 无线网无ip分配怎么办 为什么电脑的暴风影音打不开怎么办 电枪充电板进水怎么办 捡到一颗子弹该怎么办 防弹衣只保护身体那手臂怎么办? 被子被宝宝尿湿怎么办 眼睛被子弹打了怎么办 gta5买了2套衣服怎么办 gta5车被摧毁了怎么办 gta5车被损坏了怎么办 头盔玻璃磨花了怎么办 浇花喷水壶坏了怎么办 电力专用光缆撞了怎么办 国防电缆挖断了怎么办 国防光缆挖断了怎么办 房门前乱挂光纤线影响住户怎么办 挂断低于限高的光缆怎么办 开大车挂住光缆怎么办 风把树枝挂断压到车该怎么办 货车柴油冻住了怎么办 尖头鞋老是折尖怎么办 打 氟氯西林疼怎么办 多余的十字绣线怎么办 硅胶类的东西沾到蓝药水怎么办? ph计斜率不到90怎么办 ph计斜率低于90怎么办 顾客说衣服起球怎么办 买的手机壳太滑怎么办 硅胶手机壳太滑怎么办 磨砂手机壳太滑怎么办 被热胶棒烫了怎么办 车钢垫子次了怎么办 【图】机组主轴密封漏水怎么办? 孕妇吃了好多杏怎么办 怀孕6个月吃了好多杏怎么办 白色纯棉衣服染色了怎么办 红色硅胶壳黑了怎么办