先用集合将封装在Server端的Client对象储存起来,再在Client类中使用一个Sent()方法,将客户端发来的每个信息用For循环将信息发给储存起来的每一个Client对象,
01 import java.net.*;
02 import java.io.*;
03 import java.util.*;
04
05 public class ChatServer {
06 boolean started = false;
07 Socket s = null;
08 ServerSocket ss = null;
09 List
10
11 public static void main(String[] args) {
12 new ChatServer().start();
13 }
14
15 public void start() {
16 try {
17 ss = new ServerSocket(8888);
18 started = true;
19 } catch (IOException e) {
20 System.out.println("some Exception on program");
21 }
22 try {
23 while (started) {
24 boolean connect = false;
25 s = ss.accept();
26 System.out.println("A Client Connect");
27 Client c = new Client(s);
28 Clients.add(c);
29 new Thread(c).start();
30 }
31 } catch (IOException e) {
32 System.out.println("连接出错");
33 System.exit(0);
34 }
35
36 }
37
38 class Client implements Runnable {
39 private Socket s = null;
40 private DataInputStream dis = null;
41 private DataOutputStream dos = null;
42 private boolean connect = false;
43
44 public Client(Socket s) {
45 this.s = s;
46 try {
47 dis = new DataInputStream(s.getInputStream());
48 dos = new DataOutputStream(s.getOutputStream());
49 } catch (IOException e) {
50 e.printStackTrace();
51 }
52 }
53
54 public void sent(String str) {
55 try {
56 dos.writeUTF(str);
57 } catch (IOException e) {
58 e.printStackTrace();
59 }
60 }
61
62 public void run() {
63 connect = true;
64 while (connect) {
65 try {
66 String s = dis.readUTF();
67 System.out.println(s);
68 for (int i = 0; i < Clients.size(); i++) {
69 Client c = Clients.get(i);
70 c.sent(s);
71 }
72 } catch (IOException e) {
73 System.out.println("some exception on the program");
74 System.exit(0);
75
76 } finally {
77 try {
78 if (dis == null)
79 dis.close();
80 if (dos == null)
81 dos.close();
82 if (s == null)
83 s.close(); www.2cto.com
84 } catch (IOException e) {
85 System.out.println("some exception on program");
86 System.exit(0);
87 }
88 }
89 }
90 }
91 }
92 }
作者:seaer