package text; import java.io.*; import java.net.*; import java.util.*; public class ChatServer { boolean started = false; ServerSocket ss = null; List<Client> clients = new ArrayList<Client>(); public static void main(String[] args) { new ChatServer().start1(); } public void start1() { try { ss = new ServerSocket(8888); started = true; } catch (BindException e) { System.out.println("端口使用中-----请关闭相关socket"); System.exit(0); } catch (IOException e) { System.out.println("监听失败--可能原因服务器启动失败"); } try { while (started) { Socket s = ss.accept(); Client c = new Client(s); new Thread(c).start(); clients.add(c); } } catch (IOException e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } class Client implements Runnable { private Socket s; private DataInputStream dis = null; private DataOutputStream dos = null; private boolean bconnection = false; public Client(Socket s) { this.s = s; try { dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); bconnection = true; } catch (IOException e) { e.printStackTrace(); } } public void send(String str) { try { dos.writeUTF(str); } catch (IOException e) { clients.remove(this); System.out.println("对方退出了,我从内存去掉了"); } } public void run() { //Client c = null; try { while (bconnection) { String str = dis.readUTF(); System.out.println(str); /* * for(Iterator<Client> it = * clients.iterator();it.hasNext();){ Client c = it.next(); * c.send(str);//需要锁定,故不采用 } */ for (int i = 0; i < clients.size(); i++) { Client c = clients.get(i); c.send(str); } } } catch (EOFException e) { System.out.println("Client close!!!"); } 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(); } } } } }
最近下载更多