java實現的多人聊天程序

用java實現的一個簡單的多人聊天程序
標籤: <無>

源碼與演示:源碼出處

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

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

001 package org.dxer;
002 import java.io.BufferedReader;
003 import java.io.DataInputStream;
004 import java.io.DataOutputStream;
005 import java.io.IOException;
006 import java.io.InputStreamReader;
007 import java.net.Socket;
008  
009 public 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)     

001 package org.dxer;
002 import java.io.DataInputStream;
003 import java.io.DataOutputStream;
004 import java.io.IOException;
005 import java.net.ServerSocket;
006 import java.net.Socket;
007 import java.util.ArrayList;
008  
009 public 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)     

01 package org.dxer;
02 import java.text.SimpleDateFormat;
03 import java.util.Date;
04  
05 public 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 }
發佈了12 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章