/*
* Copyright (C) 2014 Graphene
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.quna.rsc.io.socket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.ParseException;
import java.util.EnumMap;
import org.quna.rsc.ActionListener;
import org.quna.rsc.data.message.MessageType;
import org.quna.rsc.data.message.Message;
import org.quna.rsc.io.ReadWriter;
import org.quna.rsc.io.StringByteBufferConverter;
/**
*
* @author owner
*/
public class RSCSocket extends RSCBaseSocket {
final Map <MessageType, ActionListener> listenerMap;
private static final Logger logger = Logger.getLogger (RSCSocket.class.getName());
public RSCSocket(String ip, int port) {
super (ip, port, new ReadWriter());
listenerMap = new EnumMap <MessageType, ActionListener> (MessageType.class);
}
@Override
void process (ByteBuffer data) {
try {
String string = StringByteBufferConverter.decodeToString (data);
Message message = new Message (string);
ActionListener listener = listenerMap.get (message.getMessageType ());
if (listener != null) {
listener.process (message);
}
} catch (ParseException ex) {
logger.log (Level.SEVERE, "", ex);
}
}
public void write (ByteBuffer data) throws IOException {
rw.write (channel, data);
}
public void addListener (MessageType type, ActionListener listener) {
listenerMap.put (type, listener);
}
public ActionListener getListener (MessageType type) {
return listenerMap.get (type) ;
}
public ActionListener removeListener (MessageType type) {
return listenerMap.remove (type);
}
}