package com.guxuede.mina.chat;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.mina.core.IoUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import com.guxuede.mina.bean.HttpMessage;
public class ChatRoom {
private Long roomID;
private HashMap<Long,IoSession> members;
public ChatRoom(Long roomID) {
this.roomID=roomID;
members=new HashMap<Long, IoSession>();
}
public void addMember(IoSession ioSession){
if(ioSession!=null && !ioSession.containsAttribute("roomID")){
ioSession.setAttribute("roomID", roomID);
members.put(ioSession.getId(), ioSession);
}
}
public void remMember(Long id){
IoSession session=members.get(id);
if(session!=null){
session.removeAttribute("roomID");
members.remove(id);
}
}
public void remMember(IoSession ioSession){
if(ioSession!=null){
ioSession.removeAttribute("roomID");
members.remove(ioSession.getId());
}
}
public void remMemberAll(){
Iterator<IoSession> it=members.values().iterator();
while (it.hasNext()) {
IoSession session=it.next();
session.removeAttribute("roomID");
it.remove();
}
}
public void speakAll(String msg){
HttpMessage hmsg=new HttpMessage();
hmsg.body=IoBuffer.allocate(20).setAutoExpand(true).put(msg.getBytes());
hmsg.body.flip();
//System.out.println(x)
IoUtil.broadcast(hmsg, members.values());
}
public static void speakTo(String msg,IoSession session){
HttpMessage hmsg=new HttpMessage();
hmsg.body=IoBuffer.allocate(20).setAutoExpand(true).put(msg.getBytes()).flip();
session.write(hmsg);
}
public Long getRoomID() {
return roomID;
}
}