1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| package zhuchuli.chat05;
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.CopyOnWriteArrayList;
public class TMultiChat { private static CopyOnWriteArrayList<Channel> all=new CopyOnWriteArrayList<Channel>(); public static void main(String[] args) throws Exception { System.out.println("-------Server-----"); ServerSocket server=new ServerSocket(8888); while(true) { Socket client=server.accept(); System.out.println("一个客户端建立了连接"); Channel c=new Channel(client); all.add(c); new Thread(c).start(); } } static class Channel implements Runnable{ private DataInputStream dis; private DataOutputStream dos; private Socket client; private boolean isRunning; private String name; public Channel(Socket client) { this.client=client; try { dis=new DataInputStream(client.getInputStream()); dos=new DataOutputStream(client.getOutputStream()); isRunning = true; this.name=receive(); send("欢迎你回来"); sendOthers(this.name+"来到了本聊天室",true); }catch(Exception e) { System.out.println("创建对象时出异常"); release(); } } private String receive() { String msg=""; try { msg=dis.readUTF(); } catch (IOException e) { System.out.println("接收数据时出现异常"); release(); } return msg; } private void sendOthers(String msg,boolean isSys) { boolean isPrivate= msg.startsWith("@"); if(isPrivate) { int idx=msg.indexOf(":"); String targetName=msg.substring(1,idx); msg=msg.substring(idx+1); for(Channel other:all) { if(other.name.equals(targetName)) { other.send(this.name+"悄悄对你说:"+msg); break; } } }else { for(Channel other:all) { if(other == this) { continue; } if(!isSys) { other.send(this.name+"对所有人说:"+msg); }else { other.send(msg); } } } } private void send(String msg) { try { dos.writeUTF(msg); dos.flush(); } catch (IOException e) { System.out.println("写出数据时出现异常"); release(); } } private void release() { this.isRunning=false; ZhuchuliUtils.close(dis,dos,client); all.remove(this); sendOthers(this.name+"离开了本聊天室",true); } @Override public void run() { while(isRunning) { String msg=receive(); if(!msg.equals("")) { sendOthers(msg,false); } } } } }
|