package com.gu.socket.pro4; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class mulServer { List<myChannal> list=new ArrayList<myChannal>(); public static void main(String[] args) throws IOException { new mulServer().connection(); } public void connection() throws IOException{ ServerSocket server=new ServerSocket(9999); while(true){ Socket soc=server.accept(); myChannal channal=new myChannal(soc); list.add(channal); Thread t1=new Thread(channal); t1.start(); } } /** * 每一个客户端一个管道 * 输入流,输出流 * @author 谷 *成员内部类 */ private class myChannal implements Runnable{ private DataInputStream in; private DataOutputStream da; private boolean isRunning=true; public myChannal(Socket soc) { try { in=new DataInputStream(soc.getInputStream()); da=new DataOutputStream(soc.getOutputStream()); } catch (IOException e) { isRunning=false; closeUtil.closeAll(in,da); list.remove(this); } } private String receive(){ String mes=null; try { mes=in.readUTF(); } catch (IOException e) { isRunning=false; closeUtil.closeAll(in,da); list.remove(this); } return mes; } private void send(String message){ if(message==null||message.equals("")) return ; try { da.writeUTF(message); da.flush(); } catch (IOException e) { isRunning=false; closeUtil.closeAll(in,da); list.remove(this); } } //群发给其他人 private void sendOthers(){ String mes=this.receive(); for(int i=0;i<list.size();i++){ if(list.get(i)==this){ continue; } list.get(i).send(mes); } } @Override public void run() { while(isRunning){ sendOthers(); } } } }