@Override
    public void run() {
        while (true) {
            try {
                int connection = selector.select(250);
                if (connection > 0) {

                    for (SelectionKey newKey : selector.selectedKeys()) {
                        if (newKey.isReadable()) {
                            readMessages((SocketChannel) newKey.channel());
                        }
                    }
                    selector.selectedKeys().clear();
                }
                if (channel.isConnected()) {
                    writeMessages();
                }

            } catch (IOException | ClassNotFoundException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }