简单事件原形

public class EventBroadcaster {
private LinkedSetMap<String, IEventHandler> handlers = new LinkedSetMap<String, IEventHandler>(); //可能多个监听对一个事件感兴趣 


private static EventBroadcaster INSTANCE = new EventBroadcaster();


public static void register(String eventName, IEventHandler handler) {
     INSTANCE.handlers.put(eventName, handler);
}


public static void unregister(String eventName, IEventHandler handler) {
    INSTANCE.handlers.remove(eventName, handler);
}


public static void broadcast(IEvent event) {
    String name = event.getType();
   if (StringUtil.isNullOrEmpty(name)) {
        throw new RuntimeException("event type is null");
      }
   Set<IEventHandler> handlers = INSTANCE.handlers.get(name);
  if (handlers != null) {
     for (IEventHandler handler : handlers) {
           handler.handle(event);
         }
     }
   }
}


public interface IEvent {
/**
* 事件类型
* @return
*/
public String getType();
}



public interface IEventHandler extends Serializable {


public void handle(IEvent event);
}




public class LinkedSetMap<K, V> implements Iterable<Map.Entry<K, Set<V>>> {
private Map<K, Set<V>> map;


public LinkedSetMap() {
map = new LinkedHashMap<K, Set<V>>();
}


public void put(K key, V value) {
addSet(key).add(value);
}


public void put(K key, Collection<V> value) {
addSet(key).addAll(value);
}


private Set<V> addSet(K key) {
Set<V> set = map.get(key);
if (set == null) {
set = new LinkedHashSet<V>();
map.put(key, set);
}
return set;
}


public void remove(K key, V value) {
Set<V> set = map.get(key);
if (set != null) {
set.remove(value);
if (set.isEmpty()) {
map.remove(key);
}
}
}


public void removeAll() {
map.clear();
}


public Set<V> get(K key) {
return map.get(key);
}


public int size() {
return map.size();
}


public Iterator<Map.Entry<K, Set<V>>> iterator() {
return map.entrySet().iterator();
}
}


第二种方式


public interface ServerListener {

 
   public void onError(String error);

   /**
    * 当有客户端发来请求时触发本事件
    */
   public void onAccept() throws Exception;

   /**
    * 当服务端接受客户端请求后触发本事件
    * @param request 客户端请求
    */
   public void onAccepted(ChannelHandlerContext context) throws Exception;

   /**
    * 当客户端发来数据,并已被服务器控制线程正确读取时,触发该事件
    * @param request 客户端请求
    */
   public void onRead(ChannelHandlerContext context) throws Exception;

   /**
    * 当可以向客户端发送请求触发本事件
    * @param request 客户端请求
    */
   public void onWrite(ChannelHandlerContext context) throws Exception;

   /**
    * 当客户端与服务器结束连接后触发本事件
    * @param request 客户端请求
    */
   public void onClosed(ChannelHandlerContext context) throws Exception;
}


public abstract class EventAdapter implements ServerListener {
    public EventAdapter() {
    }
    public void onError(String error) {
    }
    public void onAccept() throws Exception {
    }
    public void onAccepted(ChannelHandlerContext context)  throws Exception {
    }
    public void onRead(ChannelHandlerContext context)  throws Exception {
    }
    public void onWrite(ChannelHandlerContext context)  throws Exception {
    }
    public void onClosed(ChannelHandlerContext context)  throws Exception{
    }
}


public class ServerHandler extends EventAdapter {
    public ServerHandler() {
    }

    public void onAccept() throws Exception {
        System.out.println("#onAccept()");
    }

    public void onAccepted(ChannelHandlerContext request) throws Exception {
        System.out.println("#onAccepted()");
    }

    public void onRead(ChannelHandlerContext context) throws Exception {
        System.out.println("#onRead()");
        SocketChannel channel = context.getChannel();  
        ByteBuffer buffer = ByteBuffer.allocate(100);  
        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("服务端收到信息:"+msg);  
      
    }

    public void onWrite(ChannelHandlerContext context) throws Exception {
          System.out.println("#onWrite()");
          SocketChannel channel = context.getChannel(); 
          ByteBuffer buffer = ByteBuffer.wrap("receive data".getBytes());  
          channel.write(buffer);
       //   Notifier.fireOnClosed(context);
    }

    public void onClosed(ChannelHandlerContext context) throws Exception {
          System.out.println("#onClosed()");        
          SocketChannel channel = context.getChannel(); 
          channel.close();
    }

    public void onError(String error) {
        System.out.println("#onAError(): " + error);
    }
}


public class Notifier {
    private static ArrayList listeners = null;
    private static Notifier instance = null;

    private Notifier() {
        listeners = new ArrayList();
    }

  
    public static synchronized Notifier getNotifier() {
        if (instance == null) {
            instance = new Notifier();
            return instance;
        }
        else return instance;
    }

    public void addListener(ServerListener l) {
        synchronized (listeners) {
            if (!listeners.contains(l))
                listeners.add(l);
        }
    }

    public static void fireOnAccept() throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onAccept();
    }

    public static void fireOnAccepted(ChannelHandlerContext context) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onAccepted(context);
    }

    public static void  fireOnRead(ChannelHandlerContext context) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onRead(context);

    }

    public static void fireOnWrite(ChannelHandlerContext request)  throws Exception  {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onWrite(request);

    }

    public static void fireOnClosed(ChannelHandlerContext request) throws Exception {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onClosed(request);
    }

    public static void fireOnError(String error) {
        for (int i = listeners.size() - 1; i >= 0; i--)
            ( (ServerListener) listeners.get(i)).onError(error);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值