public NetObject listen(){
        NetObject ret = new NetObject();
        byte[] data = null;
        try {
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = keys.iterator();

            while(keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();

                // Incoming connections
                if(key.isAcceptable()){
                    // get server socket
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    // accept new socket
                    SocketChannel sc = ssc.accept();
                    // configure new socket as non-blocking
                    sc.configureBlocking(false);
                    // register new socket to selector
                    SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_READ);
                    // save socket to connection map
                    SocketInfo sock = new SocketInfo(sc,selectionKey);
                    socks.put(connections, sock);
                    connections++;

                    ret.type = NetObject.NetType.CONNECTION;
                    ret.sock = sc;

                }
                // Incoming data
                else if(key.isReadable()){
                    SocketChannel sc = (SocketChannel) key.channel();

                    if(fileServer){
                        ret.sock = sc;
                        ret.type = NetObject.NetType.DATA;
                        continue;
                    }

                    readBuffer.clear();
                    // Switch to read mode


                    int bufRead = sc.read(readBuffer);

                    readBuffer.flip();

                    if(bufRead < 0){
                        //System.out.println("connections lost from one slave");
                        // Remove from select list
                        key.cancel();
                        // Remove from sock list
                        Object[] set = socks.keySet().toArray();
                        for(int i = 0; i < set.length; i++){
                            if(socks.get(set[i]).getKey().equals(key)){
                                socks.remove(set[i]);
                            }
                        }
                        ret.type = NetObject.NetType.EXCEPTION;
                        continue;
                    }

                    data = new byte[readBuffer.remaining()];
                    readBuffer.get(data);
                    readBuffer.clear();
                    ret.type = NetObject.NetType.DATA;
                    ret.data = data;
                    ret.sock = sc;

                }
                keyIterator.remove();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ret;
    }