packagecom.example.qmik.framework;importjava.io.BufferedOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.SocketAddress;importjava.util.ArrayList;importjava.util.List;/** 功能:客户端连接监听器
* 时间:2013/06/07
* 作者:M1301001*/
public class IoSocketListener implementsRunnable {private List socketList=new ArrayList();private int serverPort=17171;privateServerSocket socket;publicIoSocketListener(){try{this.socket=new ServerSocket(this.serverPort);
}catch(IOException e) {
e.printStackTrace();
}
}
@Overridepublic voidrun() {try{while(true){
Socket client= this.socket.accept();this.socketList.add(client);
SocketAddress caddress=client.getRemoteSocketAddress();
String ip=caddress.toString();this.sendMsg(client,ip);
Thread h=new Thread(newIoClientListener(client));
h.start();
}
}catch(IOException e) {
e.printStackTrace();
}
}/** 释放资源*/
public voidonDestroy(){if(this.socket!=null){try{for(Socket item:this.socketList){
item.close();
}this.socket.close();
}catch(IOException e) {return;
}
}
}/** 发送消息到客户端*/
public synchronized voidsendMsg(Socket client,String msg) {try{
BufferedOutputStream out= newBufferedOutputStream(client.getOutputStream());
out.write(msg.getBytes("utf-8"));
out.flush();
}catch(Exception e) {
e.printStackTrace();
}
}
}