diff --git a/src/zutil/converter/Converter.java b/src/zutil/converter/Converter.java index f490f4e..0515760 100755 --- a/src/zutil/converter/Converter.java +++ b/src/zutil/converter/Converter.java @@ -161,30 +161,24 @@ public class Converter { * @return the associated object. */ public static Object toObject(byte[] bytes) throws Exception{ - Object object = null; - + Object object; ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); object = ois.readObject(); ois.close(); return object; } - + /** - * Converts an array of bytes back to its constituent object. The - * input array is assumed to have been created from the original object. + * Reads the first Java Serialized object from a stream. * - * @param bytes the byte array to convert. - * @return the associated object. + * @param input the stream to read from + * @return an parsed object. */ - public static Object toObject(DynamicByteArrayStream bytes) throws Exception{ - Object object = null; - - ObjectInputStream ois = new ObjectInputStream(bytes); - object = ois.readObject(); - ois.close(); - - return object; + public static Object toObject(InputStream input) throws Exception{ + ObjectInputStream ois = new ObjectInputStream(input); + // Don't close the stream as it will close the underlying stream. + return ois.readObject(); } diff --git a/src/zutil/log/net/NetLogExceptionMessage.java b/src/zutil/log/net/NetLogExceptionMessage.java old mode 100644 new mode 100755 index 71f8402..670ca60 --- a/src/zutil/log/net/NetLogExceptionMessage.java +++ b/src/zutil/log/net/NetLogExceptionMessage.java @@ -28,7 +28,7 @@ import zutil.net.nio.message.Message; import java.util.logging.LogRecord; -public class NetLogExceptionMessage extends Message { +public class NetLogExceptionMessage implements Message { private static final long serialVersionUID = 1L; private int count; diff --git a/src/zutil/log/net/NetLogMessage.java b/src/zutil/log/net/NetLogMessage.java old mode 100644 new mode 100755 index 44c673a..ce5ecf0 --- a/src/zutil/log/net/NetLogMessage.java +++ b/src/zutil/log/net/NetLogMessage.java @@ -30,7 +30,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.LogRecord; -public class NetLogMessage extends Message { +public class NetLogMessage implements Message { private static final long serialVersionUID = 1L; private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy--MM-dd HH:mm:ss"); @@ -41,7 +41,8 @@ public class NetLogMessage extends Message { private String className; private String methodName; private String log; - + + public NetLogMessage(String level, long timestamp, String log){ this.level = level; this.timestamp = timestamp; diff --git a/src/zutil/log/net/NetLogStatusMessage.java b/src/zutil/log/net/NetLogStatusMessage.java old mode 100644 new mode 100755 index 2195871..32e4a7a --- a/src/zutil/log/net/NetLogStatusMessage.java +++ b/src/zutil/log/net/NetLogStatusMessage.java @@ -26,7 +26,7 @@ package zutil.log.net; import zutil.net.nio.message.Message; -public class NetLogStatusMessage extends Message{ +public class NetLogStatusMessage implements Message{ private static final long serialVersionUID = 1L; public long totalMemory; diff --git a/src/zutil/net/nio/NioClient.java b/src/zutil/net/nio/NioClient.java index 7f9e240..0e36ee0 100755 --- a/src/zutil/net/nio/NioClient.java +++ b/src/zutil/net/nio/NioClient.java @@ -25,12 +25,11 @@ package zutil.net.nio; import zutil.net.nio.message.Message; -import zutil.net.nio.message.RequestResponseMessage; -import zutil.net.nio.response.ResponseEvent; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.SocketAddress; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; @@ -55,21 +54,24 @@ public class NioClient extends NioNetwork{ } /** - * Sends a Message to the default server + * Sends a Message to the connected server * * @param data the data to be sent */ public void send(Message data) throws IOException { send(remoteAddress, data); } - + /** - * This method is for the Client to send a message to the server - * - * @param handler the response handler - * @param data the data to send + * Sends a Message to the connected server + * + * @param data the data to be sent */ - public void send(ResponseEvent handler, RequestResponseMessage data) throws IOException { - send(remoteAddress, handler, data); + public void send(byte[] data) throws IOException { + send(remoteAddress, data); } + + public SocketAddress getRemoteAddress(){ + return remoteAddress; + } } diff --git a/src/zutil/net/nio/NioNetwork.java b/src/zutil/net/nio/NioNetwork.java index 7bf686d..9971c7b 100755 --- a/src/zutil/net/nio/NioNetwork.java +++ b/src/zutil/net/nio/NioNetwork.java @@ -26,12 +26,8 @@ package zutil.net.nio; import zutil.converter.Converter; import zutil.log.LogUtil; -import zutil.net.nio.message.RequestResponseMessage; -import zutil.net.nio.message.SystemMessage; -import zutil.net.nio.response.ResponseEvent; import zutil.net.nio.server.ChangeRequest; import zutil.net.nio.server.ClientData; -import zutil.net.nio.worker.SystemWorker; import zutil.net.nio.worker.Worker; import java.io.IOException; @@ -57,7 +53,6 @@ public abstract class NioNetwork implements Runnable { // The buffer into which we'll read data when it's available private ByteBuffer readBuffer = ByteBuffer.allocate(8192); protected Worker worker; - protected SystemWorker systemWorker; // This map contains all the clients that are connected protected Map clients = new HashMap(); @@ -85,7 +80,6 @@ public abstract class NioNetwork implements Runnable { this.localAddress = localAddress; // init selector this.selector = initSelector(); - this.systemWorker = new SystemWorker(this); // init traffic thread new Thread(this).start(); } @@ -128,13 +122,6 @@ public abstract class NioNetwork implements Runnable { send(address, Converter.toBytes(data)); } - public void send(SocketAddress address, ResponseEvent handler, RequestResponseMessage data) throws IOException { - // Register the response handler - systemWorker.addResponseHandler(handler, data); - - send(address, Converter.toBytes(data)); - } - /** * Queues a message to be sent * @@ -168,8 +155,8 @@ public abstract class NioNetwork implements Runnable { public void run() { - logger.fine("NioNetwork Started."); - while (true) { + logger.info("NioNetwork Started."); + while (selector.isOpen()) { try { // Handle any pending changes synchronized (pendingChanges) { @@ -196,36 +183,36 @@ public abstract class NioNetwork implements Runnable { logger.finest("selector is awake"); // Iterate over the set of keys for which events are available - Iterator selectedKeys = selector.selectedKeys().iterator(); - while (selectedKeys.hasNext()) { - SelectionKey key = selectedKeys.next(); - selectedKeys.remove(); - logger.finest("KeyOP: "+key.interestOps()+" isAcceptable: "+SelectionKey.OP_ACCEPT+" isConnectible: "+SelectionKey.OP_CONNECT+" isWritable: "+SelectionKey.OP_WRITE+" isReadable: "+SelectionKey.OP_READ); + if (selector.isOpen()) { + Iterator selectedKeys = selector.selectedKeys().iterator(); + while (selectedKeys.hasNext()) { + SelectionKey key = selectedKeys.next(); + selectedKeys.remove(); + logger.finest("KeyOP: " + key.interestOps() + " isAcceptable: " + SelectionKey.OP_ACCEPT + " isConnectible: " + SelectionKey.OP_CONNECT + " isWritable: " + SelectionKey.OP_WRITE + " isReadable: " + SelectionKey.OP_READ); - if (key.isValid()) { - // Check what event is available and deal with it - if (key.isAcceptable()) { - logger.finest("Accepting Connection!!"); - accept(key); - } - else if (key.isConnectable()) { - logger.finest("Establishing Connection!!"); - establishConnection(key); - } - else if (key.isWritable()) { - logger.finest("Writing"); - write(key); - } - else if (key.isReadable()) { - logger.finest("Reading"); - read(key); - } - } - } + if (key.isValid()) { + // Check what event is available and deal with it + if (key.isAcceptable()) { + logger.finest("Accepting Connection!!"); + accept(key); + } else if (key.isConnectable()) { + logger.finest("Establishing Connection!!"); + establishConnection(key); + } else if (key.isWritable()) { + logger.finest("Writing"); + write(key); + } else if (key.isReadable()) { + logger.finest("Reading"); + read(key); + } + } + } + } } catch (Exception e) { e.printStackTrace(); } } + logger.info("Shutting down NioNetwork"); } /** @@ -309,7 +296,7 @@ public abstract class NioNetwork implements Runnable { */ private void read(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); - InetSocketAddress remoteAdr = (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress(); + SocketAddress remoteAdr = socketChannel.socket().getRemoteSocketAddress(); // Clear out our read buffer so it's ready for new data readBuffer.clear(); @@ -341,43 +328,25 @@ public abstract class NioNetwork implements Runnable { } // Make a correctly sized copy of the data before handing it to the client - byte[] rspByteData = new byte[numRead]; - System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead); + //byte[] rspByteData = new byte[numRead]; + //System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead); try{ - Object rspData = Converter.toObject(rspByteData); - handleReceivedMessage(socketChannel, rspData); + Object rspData = Converter.toObject(readBuffer.array()); + + // Hand the data off to our worker thread + if (worker != null) { + logger.finer("Handling incoming message..."); + worker.processData(this, socketChannel.getRemoteAddress(), rspData); + } else { + logger.fine("No worker set, message unhandled!"); + } }catch(Exception e){ e.printStackTrace(); } } - private void handleReceivedMessage(SocketChannel socketChannel, Object rspData){ - logger.finer("Handling incoming message..."); - - try { - if (rspData instanceof SystemMessage) { - if (systemWorker != null) { - logger.finest("Handling system message"); - systemWorker.processData(this, socketChannel.getRemoteAddress(), rspData); - } else { - logger.finer("Unhandled system message!"); - } - } else { - // Hand the data off to our worker thread - if (worker != null) { - logger.finest("Handling generic worker message"); - worker.processData(this, socketChannel.getRemoteAddress(), rspData); - } else { - logger.fine("Unhandled message!"); - } - } - }catch (IOException e){ - e.printStackTrace(); - } - } - private ClientData registerSocketChannel(SocketChannel socket){ InetSocketAddress remoteAdr = (InetSocketAddress) socket.socket().getRemoteSocketAddress(); @@ -395,7 +364,7 @@ public abstract class NioNetwork implements Runnable { /** - * Close a ongoing connection + * Close a specific ongoing connection */ protected void closeConnection(InetSocketAddress address) throws IOException{ closeConnection(getSocketChannel(address)); @@ -406,14 +375,17 @@ public abstract class NioNetwork implements Runnable { socketChannel.keyFor(selector).cancel(); } - - - /*public void close() throws IOException{ + /** + * Close all connections + */ + public void close() throws IOException{ if(serverChannel != null){ serverChannel.close(); serverChannel.keyFor(selector).cancel(); } - selector.close(); - }*/ - + clients.clear(); + pendingChanges.clear(); + pendingWriteData.clear(); + selector.close(); + } } diff --git a/src/zutil/net/nio/message/EchoMessage.java b/src/zutil/net/nio/message/EchoMessage.java index 53e17af..a182a4c 100755 --- a/src/zutil/net/nio/message/EchoMessage.java +++ b/src/zutil/net/nio/message/EchoMessage.java @@ -25,18 +25,18 @@ package zutil.net.nio.message; /** - * The reciver will echo out this message to the sender + * The receiver will echo out this message to the sender * * @author Ziver */ -public abstract class EchoMessage extends Message implements SystemMessage{ +public abstract class EchoMessage implements Message{ private static final long serialVersionUID = 1L; private boolean echo = false; /** - * @return true if this message is an echo of an original message + * @return true if this message is an echo/copy of an original message */ public boolean echo() { return echo; diff --git a/src/zutil/net/nio/message/KeepAliveMessage.java b/src/zutil/net/nio/message/KeepAliveMessage.java deleted file mode 100755 index 84aa34d..0000000 --- a/src/zutil/net/nio/message/KeepAliveMessage.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - -/** - * Tells the destination that the - * source is still online - * - * @author Ziver - * - */ -public class KeepAliveMessage extends Message implements SystemMessage{ - - private static final long serialVersionUID = 1L; - -} diff --git a/src/zutil/net/nio/message/Message.java b/src/zutil/net/nio/message/Message.java old mode 100644 new mode 100755 index 6785e12..539c760 --- a/src/zutil/net/nio/message/Message.java +++ b/src/zutil/net/nio/message/Message.java @@ -26,8 +26,6 @@ package zutil.net.nio.message; import java.io.Serializable; -public class Message implements Serializable{ - private static final long serialVersionUID = 1L; - +public interface Message extends Serializable{ } diff --git a/src/zutil/net/nio/message/SystemMessage.java b/src/zutil/net/nio/message/SystemMessage.java deleted file mode 100755 index 5d50598..0000000 --- a/src/zutil/net/nio/message/SystemMessage.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - -/** - * A message that implements this will be - * handeld internaly by the network engine - * - * @author Ziver - * - */ -public interface SystemMessage { - -} diff --git a/src/zutil/net/nio/response/PrintRsp.java b/src/zutil/net/nio/response/PrintResponseHandler.java old mode 100644 new mode 100755 similarity index 89% rename from src/zutil/net/nio/response/PrintRsp.java rename to src/zutil/net/nio/response/PrintResponseHandler.java index 32bcac6..e346fed --- a/src/zutil/net/nio/response/PrintRsp.java +++ b/src/zutil/net/nio/response/PrintResponseHandler.java @@ -1,36 +1,35 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.response; - -import zutil.io.MultiPrintStream; - -public class PrintRsp extends ResponseEvent{ - - @Override - protected void responseEvent(Object rsp) { - MultiPrintStream.out.println(rsp); - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.response; + + +public class PrintResponseHandler extends ResponseHandler { + + @Override + protected void responseEvent(Object rsp) { + System.out.println(rsp); + } + +} diff --git a/src/zutil/net/nio/message/RequestResponseMessage.java b/src/zutil/net/nio/response/RequestResponseMessage.java similarity index 97% rename from src/zutil/net/nio/message/RequestResponseMessage.java rename to src/zutil/net/nio/response/RequestResponseMessage.java index 9f255db..1d955ee 100755 --- a/src/zutil/net/nio/message/RequestResponseMessage.java +++ b/src/zutil/net/nio/response/RequestResponseMessage.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package zutil.net.nio.message; +package zutil.net.nio.response; /** * This interface defines a request response flow where a request diff --git a/src/zutil/net/nio/response/ResponseEvent.java b/src/zutil/net/nio/response/ResponseEvent.java deleted file mode 100644 index 21d660e..0000000 --- a/src/zutil/net/nio/response/ResponseEvent.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.response; - - -public abstract class ResponseEvent { - private Object rsp = null; - - public synchronized boolean handleResponse(Object rsp) { - this.rsp = rsp; - notify(); - return true; - } - - /** - * Blocks the Thread until there is a response - */ - public synchronized void waitForResponse() { - while(!gotResponse()) { - try { - this.wait(); - } catch (InterruptedException e) {} - } - - responseEvent(rsp); - } - - /** - * Handles the response - */ - public void handleResponse(){ - if(gotResponse()){ - responseEvent(rsp); - } - } - - /** - * @return If there is an response - */ - public boolean gotResponse(){ - return (rsp != null); - } - - protected abstract void responseEvent(Object rsp); -} diff --git a/src/zutil/net/nio/response/ResponseHandler.java b/src/zutil/net/nio/response/ResponseHandler.java old mode 100644 new mode 100755 index 3cd1968..a019398 --- a/src/zutil/net/nio/response/ResponseHandler.java +++ b/src/zutil/net/nio/response/ResponseHandler.java @@ -24,42 +24,35 @@ package zutil.net.nio.response; -import java.util.LinkedList; -import java.util.List; +// TODO: this class has a strange structure, should be refactored +public abstract class ResponseHandler { + private Object rsp = null; - -public abstract class ResponseHandler implements Runnable{ - private List queue = new LinkedList(); - - public ResponseHandler(){ - - } - - public synchronized void addResponseEvent(ResponseEvent re){ - queue.add(re); + public synchronized void handleResponse(Object rsp) { + this.rsp = rsp; + responseEvent(rsp); notify(); } - - public synchronized void removeResponseEvent(ResponseEvent re){ - queue.remove(re); - } - - public void run() { - while(true) { + + /** + * Blocks the calling thread until there is a response + */ + public void waitForResponse() { + while(!gotResponse()) { try { - this.wait(); + synchronized (this) { + this.wait(); + } } catch (InterruptedException e) {} - - update(); } } - public synchronized void update(){ - while(!queue.isEmpty()){ - queue.get(0).handleResponse(); - if(queue.get(0).gotResponse()){ - queue.remove(0); - } - } + /** + * @return true if a response has been received + */ + public boolean gotResponse(){ + return (rsp != null); } + + protected abstract void responseEvent(Object rsp); } diff --git a/src/zutil/net/nio/message/StringResponseMessage.java b/src/zutil/net/nio/response/StringResponseMessage.java similarity index 91% rename from src/zutil/net/nio/message/StringResponseMessage.java rename to src/zutil/net/nio/response/StringResponseMessage.java index 1333593..f447d15 100755 --- a/src/zutil/net/nio/message/StringResponseMessage.java +++ b/src/zutil/net/nio/response/StringResponseMessage.java @@ -22,33 +22,33 @@ * THE SOFTWARE. */ -package zutil.net.nio.message; +package zutil.net.nio.response; +import zutil.net.nio.message.EchoMessage; + public class StringResponseMessage extends EchoMessage implements RequestResponseMessage { private static final long serialVersionUID = 1L; private long responseId; private String msg; - + + public StringResponseMessage(String msg){ this.msg = msg; responseId = (long)(Math.random()*Long.MAX_VALUE); } - - public String getString(){ - return msg; - } - + + + public long getResponseId() { + return responseId; + } + public void setString(String msg){ this.msg = msg; } public String toString(){ - return getString(); + return msg; } - - public long getResponseId() { - return responseId; - } -} +} \ No newline at end of file diff --git a/src/zutil/net/nio/worker/EchoWorker.java b/src/zutil/net/nio/worker/EchoWorker.java deleted file mode 100755 index d2f4ae1..0000000 --- a/src/zutil/net/nio/worker/EchoWorker.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.worker; - -import java.io.IOException; - - -public class EchoWorker extends ThreadedEventWorker { - - @Override - public void messageEvent(WorkerEventData dataEvent) { - try { - // Return to sender - dataEvent.network.send(dataEvent.remoteAddress, dataEvent.data); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - -} diff --git a/src/zutil/net/nio/worker/SystemWorker.java b/src/zutil/net/nio/worker/StandardWorker.java similarity index 52% rename from src/zutil/net/nio/worker/SystemWorker.java rename to src/zutil/net/nio/worker/StandardWorker.java index b5b1979..e66192f 100755 --- a/src/zutil/net/nio/worker/SystemWorker.java +++ b/src/zutil/net/nio/worker/StandardWorker.java @@ -1,118 +1,126 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.worker; - -import zutil.log.LogUtil; -import zutil.net.nio.NioNetwork; -import zutil.net.nio.message.Message; -import zutil.net.nio.message.EchoMessage; -import zutil.net.nio.message.RequestResponseMessage; -import zutil.net.nio.response.ResponseEvent; - -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Logger; - - -public class SystemWorker extends ThreadedEventWorker { - private static Logger logger = LogUtil.getLogger(); - - private NioNetwork nio; - // Maps a responseId to a RspHandler - private Map rspEvents = new HashMap<>(); - // Different services listening on specific messages - private Map, ThreadedEventWorker> services = new HashMap<>(); - - - - /** - * Creates a new SystemWorker - */ - public SystemWorker(NioNetwork nio){ - this.nio = nio; - } - - - - @Override - public void messageEvent(WorkerEventData event) { - try { - logger.finer("System Message: "+event.data.getClass().getName()); - if(event.data instanceof Message){ - if(event.data instanceof EchoMessage && ((EchoMessage)event.data).echo()){ - // Echos back the received message - ((EchoMessage)event.data).received(); - logger.finer("Echoing Message: "+event.data); - nio.send(event.remoteAddress, event.data); - } - else if(event.data instanceof RequestResponseMessage && - rspEvents.get(((RequestResponseMessage)event.data).getResponseId()) != null){ - long responseId = ((RequestResponseMessage)event.data).getResponseId(); - // Look up the handler for this channel - ResponseEvent handler = rspEvents.get(responseId); - // And pass the response to it - handler.handleResponse(event.data); - rspEvents.remove(responseId); - logger.finer("Response Request Message: "+event.data); - } - else{ - // Check mapped workers - if(services.containsKey(event.data.getClass())){ - services.get(event.data.getClass()).messageEvent(event); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Maps a Worker to a specific message - * - * @param messageClass the received message class - * @param worker the worker that should handle the specified message type - */ - public void registerWorker(Class messageClass, ThreadedEventWorker worker){ - services.put(messageClass, worker); - } - - /** - * Un-maps a message class to a worker - * - * @param messageClass the received message class - */ - public void unregisterWorker(Class messageClass){ - services.remove(messageClass); - } - - /** - * Connects a ResponseHandler to a specific message object - */ - public void addResponseHandler(ResponseEvent handler, RequestResponseMessage data){ - rspEvents.put(data.getResponseId(), handler); - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.worker; + +import zutil.converter.Converter; +import zutil.log.LogUtil; +import zutil.net.nio.NioNetwork; +import zutil.net.nio.message.Message; +import zutil.net.nio.message.EchoMessage; +import zutil.net.nio.response.RequestResponseMessage; +import zutil.net.nio.response.ResponseHandler; + +import java.io.IOException; +import java.net.SocketAddress; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + + +public class StandardWorker extends ThreadedEventWorker { + private static Logger logger = LogUtil.getLogger(); + + private NioNetwork nio; + // Maps a responseId to a RspHandler + private Map rspEvents = new HashMap<>(); + // Different services listening on specific messages + private Map, ThreadedEventWorker> services = new HashMap<>(); + + + + /** + * Creates a new StandardWorker + */ + public StandardWorker(NioNetwork nio){ + this.nio = nio; + } + + + + @Override + public void messageEvent(WorkerEventData event) { + try { + logger.finer("Message: "+event.data.getClass().getName()); + + if(event.data instanceof EchoMessage && !((EchoMessage)event.data).echo()){ + // Echo back the received message + ((EchoMessage)event.data).received(); + logger.finer("Echoing Message: "+event.data); + nio.send(event.remoteAddress, event.data); + } + else if(event.data instanceof RequestResponseMessage && + rspEvents.get(((RequestResponseMessage)event.data).getResponseId()) != null){ + long responseId = ((RequestResponseMessage)event.data).getResponseId(); + // Look up the handler for this channel + ResponseHandler handler = rspEvents.get(responseId); + // And pass the response to it + handler.handleResponse(event.data); + rspEvents.remove(responseId); + logger.finer("Response Request Message: "+event.data); + } + else{ + // Check mapped workers + if(services.containsKey(event.data.getClass())){ + services.get(event.data.getClass()).messageEvent(event); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Maps a Worker to a specific message + * + * @param messageClass the received message class + * @param worker the worker that should handle the specified message type + */ + public void registerWorker(Class messageClass, ThreadedEventWorker worker){ + services.put(messageClass, worker); + } + + /** + * Un-maps a message class to a worker + * + * @param messageClass the received message class + */ + public void unregisterWorker(Class messageClass){ + services.remove(messageClass); + } + + /** + * Send a message with a defined response handler + * + * @param address the target host for the message + * @param message the message object + * @param handler the handler that should be called when a response is received + */ + public void send(SocketAddress address, RequestResponseMessage message, ResponseHandler handler) throws IOException { + // Register the response handler + rspEvents.put(message.getResponseId(), handler); + + nio.send(address, Converter.toBytes(message)); + } +} diff --git a/src/zutil/net/nio/worker/Worker.java b/src/zutil/net/nio/worker/Worker.java index 81aada1..8d2b390 100755 --- a/src/zutil/net/nio/worker/Worker.java +++ b/src/zutil/net/nio/worker/Worker.java @@ -32,8 +32,9 @@ import java.util.List; public abstract class Worker { - private LinkedList queue = new LinkedList(); - + private LinkedList queue = new LinkedList<>(); + + public void processData(NioNetwork server, SocketAddress remote, Object data) { synchronized(queue) { queue.add(new WorkerEventData(server, remote, data)); @@ -50,7 +51,7 @@ public abstract class Worker { } /** - * Polls a event from the list or waits until there is a event + * Polls a event from the list or blocks until there is a event available * * @return the next event */ diff --git a/src/zutil/net/nio/worker/WorkerEventData.java b/src/zutil/net/nio/worker/WorkerEventData.java index 67f83d5..6a484a5 100755 --- a/src/zutil/net/nio/worker/WorkerEventData.java +++ b/src/zutil/net/nio/worker/WorkerEventData.java @@ -34,7 +34,8 @@ public class WorkerEventData { public NioNetwork network; public SocketAddress remoteAddress; public Object data; - + + public WorkerEventData(NioNetwork server, SocketAddress remoteAddress, Object data) { this.network = server; this.remoteAddress = remoteAddress; diff --git a/src/zutil/net/nio/message/ChatMessage.java b/src/zutil/net/nio/worker/chat/ChatMessage.java old mode 100644 new mode 100755 similarity index 93% rename from src/zutil/net/nio/message/ChatMessage.java rename to src/zutil/net/nio/worker/chat/ChatMessage.java index 0d5cf0f..1e29977 --- a/src/zutil/net/nio/message/ChatMessage.java +++ b/src/zutil/net/nio/worker/chat/ChatMessage.java @@ -1,69 +1,71 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - -public class ChatMessage extends Message{ - private static final long serialVersionUID = 1L; - - public static enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE}; - - public ChatMessageType type; - public String msg; - public String room; - - /** - * Registers the user to the main chat - * - * @param name Name of user - */ - public ChatMessage(){ - this("", "", ChatMessageType.REGISTER); - } - - /** - * Registers the user to the given room - * - * @param room The room to register to - */ - public ChatMessage(String room){ - this("", room, ChatMessageType.REGISTER); - } - - /** - * Sends a message to the given room - * - * @param msg The message - * @param room The room - */ - public ChatMessage(String msg, String room){ - this(msg, room, ChatMessageType.MESSAGE); - } - - public ChatMessage(String msg, String room, ChatMessageType type){ - this.msg = msg; - this.room = room; - this.type = type; - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.worker.chat; + +import zutil.net.nio.message.Message; + +public class ChatMessage implements Message { + private static final long serialVersionUID = 1L; + + public static enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE}; + + public ChatMessageType type; + public String msg; + public String room; + + /** + * Registers the user to the main chat + * + * @param name Name of user + */ + public ChatMessage(){ + this("", "", ChatMessageType.REGISTER); + } + + /** + * Registers the user to the given room + * + * @param room The room to register to + */ + public ChatMessage(String room){ + this("", room, ChatMessageType.REGISTER); + } + + /** + * Sends a message to the given room + * + * @param msg The message + * @param room The room + */ + public ChatMessage(String msg, String room){ + this(msg, room, ChatMessageType.MESSAGE); + } + + public ChatMessage(String msg, String room, ChatMessageType type){ + this.msg = msg; + this.room = room; + this.type = type; + } +} diff --git a/src/zutil/net/nio/worker/chat/ChatService.java b/src/zutil/net/nio/worker/chat/ChatService.java index 23e1bb6..0adb61e 100755 --- a/src/zutil/net/nio/worker/chat/ChatService.java +++ b/src/zutil/net/nio/worker/chat/ChatService.java @@ -25,14 +25,10 @@ package zutil.net.nio.worker.chat; import zutil.log.LogUtil; -import zutil.net.nio.NioNetwork; -import zutil.net.nio.message.ChatMessage; -import zutil.net.nio.message.Message; import zutil.net.nio.worker.ThreadedEventWorker; import zutil.net.nio.worker.WorkerEventData; import java.net.SocketAddress; -import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.LinkedList; import java.util.logging.Logger; diff --git a/src/zutil/net/nio/worker/grid/GridClient.java b/src/zutil/net/nio/worker/grid/GridClient.java index b3b5172..2a47905 100755 --- a/src/zutil/net/nio/worker/grid/GridClient.java +++ b/src/zutil/net/nio/worker/grid/GridClient.java @@ -26,7 +26,6 @@ package zutil.net.nio.worker.grid; import zutil.io.MultiPrintStream; import zutil.net.nio.NioClient; -import zutil.net.nio.message.GridMessage; import zutil.net.nio.worker.ThreadedEventWorker; import zutil.net.nio.worker.WorkerEventData; diff --git a/src/zutil/net/nio/message/GridMessage.java b/src/zutil/net/nio/worker/grid/GridMessage.java old mode 100644 new mode 100755 similarity index 84% rename from src/zutil/net/nio/message/GridMessage.java rename to src/zutil/net/nio/worker/grid/GridMessage.java index 09773fc..7a0f9bb --- a/src/zutil/net/nio/message/GridMessage.java +++ b/src/zutil/net/nio/worker/grid/GridMessage.java @@ -1,108 +1,109 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - -public class GridMessage extends Message{ - private static final long serialVersionUID = 1L; - - // Client type messages - /** Computation job return right answer **/ - public static final int COMP_SUCCESSFUL = 1; // - /** Initial static data **/ - public static final int COMP_INCORRECT = 2; // - /** Computation job return wrong answer **/ - public static final int COMP_ERROR = 3; // - /** There was an error computing **/ - public static final int REGISTER = 4; // - /** Register at the server **/ - public static final int UNREGISTER = 5; // - /** Request new computation data **/ - public static final int NEW_DATA = 6; // - - // Server type messages - /** Sending initial static data **/ - public static final int INIT_DATA = 100; - /** Sending new dynamic data **/ - public static final int COMP_DATA = 101; - - - private int type; - private int jobID; - private T data; - - /** - * Creates a new GridMessage - * - * @param type is the type of message - * @param jobID is the id of the job - */ - public GridMessage(int type){ - this(type, 0, null); - } - - /** - * Creates a new GridMessage - * - * @param type is the type of message - * @param jobID is the id of the job - */ - public GridMessage(int type, int jobID){ - this(type, jobID, null); - } - - /** - * Creates a new GridMessage - * - * @param type is the type of message - * @param jobID is the id of the job - * @param data is the data to send with this message - */ - public GridMessage(int type, int jobID, T data){ - this.type = type; - this.jobID = jobID; - this.data = data; - } - - /** - * @return the type of message - */ - public int messageType(){ - return type; - } - - /** - * @return the job id for this message - */ - public int getJobQueueID(){ - return jobID; - } - - /** - * @return the data in this message, may not always carry any data. - */ - public T getData(){ - return data; - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.worker.grid; + +import zutil.net.nio.message.Message; + +public class GridMessage implements Message { + private static final long serialVersionUID = 1L; + + // Client type messages + /** Computation job return right answer **/ + public static final int COMP_SUCCESSFUL = 1; // + /** Initial static data **/ + public static final int COMP_INCORRECT = 2; // + /** Computation job return wrong answer **/ + public static final int COMP_ERROR = 3; // + /** There was an error computing **/ + public static final int REGISTER = 4; // + /** Register at the server **/ + public static final int UNREGISTER = 5; // + /** Request new computation data **/ + public static final int NEW_DATA = 6; // + + // Server type messages + /** Sending initial static data **/ + public static final int INIT_DATA = 100; + /** Sending new dynamic data **/ + public static final int COMP_DATA = 101; + + + private int type; + private int jobId; + private T data; + + /** + * Creates a new GridMessage + * + * @param type is the type of message + */ + public GridMessage(int type){ + this(type, 0, null); + } + + /** + * Creates a new GridMessage + * + * @param type is the type of message + * @param jobId is the id of the job + */ + public GridMessage(int type, int jobId){ + this(type, jobId, null); + } + + /** + * Creates a new GridMessage + * + * @param type is the type of message + * @param jobId is the id of the job + * @param data is the data to send with this message + */ + public GridMessage(int type, int jobId, T data){ + this.type = type; + this.jobId = jobId; + this.data = data; + } + + /** + * @return the type of message + */ + public int messageType(){ + return type; + } + + /** + * @return the job id for this message + */ + public int getJobQueueID(){ + return jobId; + } + + /** + * @return the data in this message, may not always carry any data. + */ + public T getData(){ + return data; + } +} diff --git a/src/zutil/net/nio/worker/grid/GridServerWorker.java b/src/zutil/net/nio/worker/grid/GridServerWorker.java index 7fa6b63..a6d4ece 100755 --- a/src/zutil/net/nio/worker/grid/GridServerWorker.java +++ b/src/zutil/net/nio/worker/grid/GridServerWorker.java @@ -24,7 +24,6 @@ package zutil.net.nio.worker.grid; -import zutil.net.nio.message.GridMessage; import zutil.net.nio.worker.ThreadedEventWorker; import zutil.net.nio.worker.WorkerEventData; diff --git a/src/zutil/net/nio/message/GraphicsSyncMessage.java b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java old mode 100644 new mode 100755 similarity index 95% rename from src/zutil/net/nio/message/GraphicsSyncMessage.java rename to src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java index 019d34f..c46bfa8 --- a/src/zutil/net/nio/message/GraphicsSyncMessage.java +++ b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java @@ -1,55 +1,55 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - - -public class GraphicsSyncMessage extends SyncMessage{ - private static final long serialVersionUID = 1L; - - public float locX; - public float locY; - public float locZ; - - public float rotX; - public float rotY; - public float rotZ; - public float rotW; - - public GraphicsSyncMessage(String id){ - this.type = MessageType.SYNC; - this.id = id; - } - - public boolean equals(Object obj){ - if(obj instanceof GraphicsSyncMessage){ - GraphicsSyncMessage tmp = (GraphicsSyncMessage)obj; - return (tmp.locX == locX && tmp.locY == locY && - tmp.locZ == locZ && tmp.rotX == rotX && - tmp.rotY == rotY && tmp.rotZ == rotZ && - tmp.rotW == rotW); - } - return false; - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.worker.sync; + + +public class GraphicsSyncMessage extends SyncMessage{ + private static final long serialVersionUID = 1L; + + public float locX; + public float locY; + public float locZ; + + public float rotX; + public float rotY; + public float rotZ; + public float rotW; + + public GraphicsSyncMessage(String id){ + this.type = MessageType.SYNC; + this.id = id; + } + + public boolean equals(Object obj){ + if(obj instanceof GraphicsSyncMessage){ + GraphicsSyncMessage tmp = (GraphicsSyncMessage)obj; + return (tmp.locX == locX && tmp.locY == locY && + tmp.locZ == locZ && tmp.rotX == rotX && + tmp.rotY == rotY && tmp.rotZ == rotZ && + tmp.rotW == rotW); + } + return false; + } +} diff --git a/src/zutil/net/nio/worker/sync/ObjectSync.java b/src/zutil/net/nio/worker/sync/ObjectSync.java index 32aaf66..c7d9001 100755 --- a/src/zutil/net/nio/worker/sync/ObjectSync.java +++ b/src/zutil/net/nio/worker/sync/ObjectSync.java @@ -24,8 +24,6 @@ package zutil.net.nio.worker.sync; -import zutil.net.nio.message.SyncMessage; - public abstract class ObjectSync { public String id; diff --git a/src/zutil/net/nio/message/SyncMessage.java b/src/zutil/net/nio/worker/sync/SyncMessage.java similarity index 86% rename from src/zutil/net/nio/message/SyncMessage.java rename to src/zutil/net/nio/worker/sync/SyncMessage.java index c9c9195..e699a33 100755 --- a/src/zutil/net/nio/message/SyncMessage.java +++ b/src/zutil/net/nio/worker/sync/SyncMessage.java @@ -1,35 +1,42 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package zutil.net.nio.message; - -public class SyncMessage extends Message implements SystemMessage{ - private static final long serialVersionUID = 1L; - public static enum MessageType { REQUEST_ID, NEW, REMOVE, SYNC }; - - // type of message - public MessageType type; - // id of the Object - public String id; -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package zutil.net.nio.worker.sync; + +import zutil.net.nio.message.Message; + +public class SyncMessage implements Message { + private static final long serialVersionUID = 1L; + public enum MessageType { + REQUEST_ID, + NEW, + REMOVE, + SYNC + } + + // type of message + public MessageType type; + // id of the Object + public String id; +} diff --git a/src/zutil/net/nio/worker/sync/SyncService.java b/src/zutil/net/nio/worker/sync/SyncService.java index ca55e7f..f67dc05 100755 --- a/src/zutil/net/nio/worker/sync/SyncService.java +++ b/src/zutil/net/nio/worker/sync/SyncService.java @@ -25,13 +25,9 @@ package zutil.net.nio.worker.sync; import zutil.log.LogUtil; -import zutil.net.nio.NioNetwork; -import zutil.net.nio.message.Message; -import zutil.net.nio.message.SyncMessage; import zutil.net.nio.worker.ThreadedEventWorker; import zutil.net.nio.worker.WorkerEventData; -import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.logging.Logger; diff --git a/test/zutil/net/nio/NetworkClientTest.java b/test/zutil/net/nio/NetworkClientTest.java index 28b5adf..a9e71a0 100755 --- a/test/zutil/net/nio/NetworkClientTest.java +++ b/test/zutil/net/nio/NetworkClientTest.java @@ -26,8 +26,9 @@ package zutil.net.nio; import zutil.log.CompactLogFormatter; import zutil.log.LogUtil; -import zutil.net.nio.message.StringResponseMessage; -import zutil.net.nio.response.PrintRsp; +import zutil.net.nio.response.StringResponseMessage; +import zutil.net.nio.response.PrintResponseHandler; +import zutil.net.nio.worker.StandardWorker; import java.io.IOException; import java.net.InetAddress; @@ -39,21 +40,27 @@ import java.util.logging.Level; public class NetworkClientTest { public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { try { - LogUtil.setGlobalLevel(Level.ALL); + //LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); int count = 0; long time = System.currentTimeMillis()+1000*60; NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056); + StandardWorker worker = new StandardWorker(client); + client.setDefaultWorker(worker); + Thread.sleep(1000); while(time > System.currentTimeMillis()){ - PrintRsp handler = new PrintRsp(); - client.send(handler, new StringResponseMessage("StringResponseMessage: "+count)); + PrintResponseHandler handler = new PrintResponseHandler(); + worker.send(client.getRemoteAddress(), + new StringResponseMessage("StringResponseMessage: "+count), + handler); handler.waitForResponse(); //Thread.sleep(100); //System.out.println("sending.."); count++; } + client.close(); System.out.println("Message Count 1m: "+count); System.out.println("Message Count 1s: "+count/60); diff --git a/test/zutil/net/nio/NetworkServerTest.java b/test/zutil/net/nio/NetworkServerTest.java index 2b5fb1f..fd51b49 100755 --- a/test/zutil/net/nio/NetworkServerTest.java +++ b/test/zutil/net/nio/NetworkServerTest.java @@ -26,6 +26,7 @@ package zutil.net.nio; import zutil.log.CompactLogFormatter; import zutil.log.LogUtil; +import zutil.net.nio.worker.StandardWorker; import java.io.IOException; import java.security.NoSuchAlgorithmException; @@ -36,10 +37,11 @@ import java.util.logging.Level; public class NetworkServerTest { public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { try { - LogUtil.setGlobalLevel(Level.ALL); + //LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); NioServer server = new NioServer(6056); + server.setDefaultWorker(new StandardWorker(server)); while(true){ Thread.sleep(1000);