NIO first problems

Hi guys,
I experience very strange problem. Once a new connection is established and the key for the channel is registered for READ operations, the selector starts to continuosly provide me with the key having OP_READ set up:
if (selector.select() == 0)
    continue;
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext())
    SelectionKey key = (SelectionKey) it.next();
    // Accept new connection
    if (key.isAcceptable())
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        SocketChannel channel = server.accept();
        if (channel == null)
            continue;
        // Set the new channel nonblocking
        channel.configureBlocking(false);
        // Register it with the selector
        SelectionKey newKey = channel.register(selector, SelectionKey.OP_READ);
        // initialization of attachment ...
    if (key.isReadable())
        System.out.print("session index = "  +((ConnectionDescriptor)key.attachment()).session.sessionIndex);+
+System.out.print(", counter "+  ++counter);+
+System.out.println(", ops="+  key.readyOps());                   
        // read the data from channel
        if( counter == 10 ) {
            setEnabled(false);
            break;
    it.remove();
}I use a python script in order to test the server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect("localhost", 28000)
s.send(b'\x00\x01')
s.close()When I run the script I see the following output from the server:
session index = 1, counter 1, ops=1
session index = 1, counter 2, ops=1
session index = 1, counter 3, ops=1
header limit = 2
body limit = 0
process message 1
session index = 1, counter 4, ops=1
session index = 1, counter 5, ops=1
session index = 1, counter 6, ops=1
session index = 1, counter 7, ops=1
session index = 1, counter 8, ops=1
session index = 1, counter 9, ops=1
session index = 1, counter 10, ops=1some parts of the code are omitted in order to keep it clear. If I do not stop it at 10th iteration it runs into endless loop.
Why the key always says that the channel is "ready" to be read while I actually have already read the data?
Thanks a lot in advance.
Edited by: coderman on Jan 28, 2010 5:44 AM

This is an example class you can reproduce the issue with:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Iterator;
public class MyServer
    private Selector selector;
    private int sessionSequence;
    public MyServer() throws IOException
        final ServerSocketChannel mainServerChannel = ServerSocketChannel.open();
        ServerSocket mainSocket = mainServerChannel.socket();
        mainSocket.bind(new InetSocketAddress(28000));
        mainServerChannel.configureBlocking(false);
        selector = Selector.open();
        mainServerChannel.register(selector, SelectionKey.OP_ACCEPT);
        int counter = 0;
        while (true)
            if (selector.select(1000) == 0)
                continue;
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext())
                SelectionKey key = (SelectionKey) it.next();
                if (key.isAcceptable())
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    if (channel == null)
                        continue;
                    channel.configureBlocking(false);
                    SelectionKey newKey = channel.register(selector, SelectionKey.OP_READ );
                if (key.isReadable())
                    System.out.print("counter " + counter);
                    System.out.print(", ops=" + key.readyOps());
                    ByteBuffer header = ByteBuffer.allocateDirect(10);
                    try
                        ((SocketChannel) key.channel()).read(header);
                    } catch (ClosedChannelException cce)
                        // the channel has been closed by the server
                    } catch (IOException ex)
                        // networking problem. Might be also connection lost.
                    header.flip();
                    System.out.println(", header limit = " + header.limit());
                    if (++counter == 15)
                        System.exit(0);
                it.remove();
    public static void main(String[] argv)
        try
            new MyServer();
        } catch (IOException ex)
            ex.printStackTrace();
}Here is the python script:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 28000))
s.send(b'\x00\x01\x02')
s.shutdown(1)This is what I get on my computer:
counter 0, ops=1, header limit = 3
counter 1, ops=1, header limit = 0
counter 2, ops=1, header limit = 0
counter 3, ops=1, header limit = 0
counter 4, ops=1, header limit = 0
counter 5, ops=1, header limit = 0
counter 6, ops=1, header limit = 0
counter 7, ops=1, header limit = 0
counter 8, ops=1, header limit = 0
counter 9, ops=1, header limit = 0
counter 10, ops=1, header limit = 0
counter 11, ops=1, header limit = 0
counter 12, ops=1, header limit = 0
counter 13, ops=1, header limit = 0
counter 14, ops=1, header limit = 0

Similar Messages

  • NIO - Selector problem - when using more than one in same application

    Hi,
    I'm developing a multiplayer-server, which shall be able to handle at least 2000 concurrent clients. To avoid the use of 4000 threads for 2000 clients (a thread for each stream), I would like to use NIO.
    Problem:
    The server has of course a ServerSocketChannel registered with a Selector, and when clients connects, the SocketChannel's is received. IF these channels is registered (OP_READ) with the same Selector-instance as the ServerSocketChannel, there is no problem and the Selector recognizes when a registered SocketChannel is ready for OP_READ - BUT when the received SocketChannels is registered with another Selector-instance than the one the ServerSocketChannel is registered with, the Selector NEVER recognizes, when a SocketChannel is ready for OP_READ - why not and how do I solve the problem? Only one thread can service the same Selector-instance, and when both receiving many connections and read/write, this could easily be a bottleneck
    Following is the used code; 2 classes: ClientListener (has a ServerSocketChannel registered with a Selector) and ClientHandler (has another Selector where the SocketChannels is registered and a thread-pool that services all the SocketChannels, when they are ready for read/write):
    public class ClientListener {
      private static final int BACKLOG = 32;
      private int port;
      private Thread internalThread;
      private volatile boolean noStopRequested;
      private ServerSocketChannel ssc;
      private static Selector selector;
      private ClientHandler clientHandler;
      public ClientListener(ClientHandler clientHandler, String bindAddress, int port) throws InternalErrorException {
        this.clientClass = clientClass;
        this.clientHandler = clientHandler;
        this.noStopRequested = true;
        this.port = port;
        try {
          InetAddress inetAddress;
          if (bindAddress.equals(""))
            inetAddress = InetAddress.getLocalHost();
          else
            inetAddress = InetAddress.getByName(bindAddress);
          ssc = ServerSocketChannel.open();
          ssc.socket().bind(new InetSocketAddress(inetAddress, port), BACKLOG);
          ssc.configureBlocking(false);
          Runnable r = new Runnable() {
            public void run() {
              try {
                start();
              } catch (Exception e) {
                Log.echoError("ClientListener: Unexpected error: "+e.getMessage());
          internalThread = new Thread(r, "ClientHandler");
          internalThread.start();
        } catch (Exception e) {
          throw new InternalErrorException(e.getMessage());
      public static Selector selector() {
        return selector;
      private void start() {
        Log.echoSystem("ClientListener: Listening started at port "+port);
        try {
          selector = Selector.open();
          SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
          int keysAdded;
          while (noStopRequested) {
            SelectionKey key = null;
            keysAdded = selector.select(10000);
            if (keysAdded == 0)
              continue;
            Set readyKeys = selector.selectedKeys();
            Iterator i = readyKeys.iterator();
            while (i.hasNext()) {
              try {
                key = (SelectionKey)i.next();
                i.remove();
                if (key.isAcceptable()) {
                  ServerSocketChannel nextReady = (ServerSocketChannel)key.channel();
                  SocketChannel sc = nextReady.accept();
                  try {
                    clientHandler.registerClient(sc);
                  } catch (Exception e) { e.printStackTrace(); }
              } catch (CancelledKeyException cke) {
                System.out.println("ClientListener: CancelledKeyException");
        } catch (Exception e) {
          e.printStackTrace();
          try {
            ssc.close();
          } catch (IOException ioe) {/* Ignore */}
        Log.echoSystem("ClientListener: stopped");
      public void stop() {
    public class ClientHandler {
      private static final int INITIAL_WORKER_COUNT = 5;
      private int port;
      private Thread internalThread;
      private volatile boolean noStopRequested;
      private static Selector selector;
      private Manager manager;
      private WorkerPool pool;
      private ClientListener clientListener;
      public ClientHandler(Manager manager, String bindAddress, int port) throws InternalErrorException {
        this.manager = manager;
        this.noStopRequested = true;
        this.port = port;
        clientListener = new ClientListener(this, bindAddress, port);
        // initiating load-balanced worker-pool
        pool = new WorkerPool(INITIAL_WORKER_COUNT, (int)(manager.getMaxClients() * ClientWorker.CLIENT_FACTOR), 0.75f);
        for (int i=0; i < pool.getMinCount(); i++) {
          pool.addWorker(new ClientWorker(pool, manager));
        Runnable r = new Runnable() {
          public void run() {
            try {
              start();
            } catch (Exception e) {
              Log.echoError("ClientHandler: Unexpected error: "+e.getMessage());
        internalThread = new Thread(r, "ClientHandler");
        internalThread.start();
      public static Selector selector() {
        return selector;
      private void start() {
        Log.echoSystem("ClientHandler: Started");
        try {
          selector = Selector.open();
          int keysAdded;
          while (noStopRequested) {
            SelectionKey key = null;
            try {
              keysAdded = selector.select();
              Log.echoDebug("ClientHandler: out of select()");
              if (keysAdded == 0)
                continue;
              Set readyKeys = selector.selectedKeys();
              Iterator i = readyKeys.iterator();
              while (i.hasNext()) {
                try {
                  key = (SelectionKey)i.next();
                  i.remove();
                  if (key.isReadable()) {
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    ClientWorker worker = (ClientWorker)pool.getWorker();
                    worker.process(key);
                  } else if (key.isWritable()) {
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    ClientWorker worker = (ClientWorker)pool.getWorker();
                    worker.process(key);
                  } else {
                } catch (CancelledKeyException cke) {
                  Client client = (Client)key.attachment();
                  if (client != null) {
                    client.disconnect();
                    key.selector().wakeup();
            } catch (CancelledKeyException cke) {
              if (key != null) {
                Client client = (Client)key.attachment();
                if (client != null) {
                  client.disconnect();
                  key.selector().wakeup();
        } catch (Exception e) {
          e.printStackTrace();
        Log.echoSystem("ClientHandler: stopped");
      public void registerClient(SocketChannel sc) throws Exception {
        sc.configureBlocking(false);
        Client client = new Client(...);
        SelectionKey key = sc.register(selector, SelectionKey.OP_READ, client);
        key.selector().wakeup();
      public void stop() {
    }

    Ok, found the solution here: http://forum.java.sun.com/thread.jsp?forum=31&thread=282069
    "The select() method holds a lock on the selector that
    the register() method wants to acquire. The register()
    method cannot continue until the lock is relased and
    the select() method will not release it until some key
    is triggered. If this is the first key you're adding
    then select has nothing that will wake it up, ever.
    The result is, obviously, a deadlock.
    The solution is to have a queue of pending connections.
    You put your new connection in that queue. Then you
    wake up the selector and let that thread go through
    the queue, registering connections."

  • My first problem is that I have no apps on my iPod desktop. The second is that my battery died, and despite being able to charge it, it is unable to restart back up.

    My first problem is that I have no apps on my iPod desktop. After using my computer to install something onto my iPod 5, it somehow disconnected. When i restarted the iPod, some apps (Safari, FaceTime, Game Center, App Store, iTunes Store, Camera, and some others disappeared. Apps like Flashlight and Jetpack Joyride which I had previousyl downloaded from the App Store were still there. I wanted to get the aforementioned apps back, so i decided to back-up my iPod to iTunes. The downloaded apps weren't able to be backed up ("authentication problems") but some apps like Tips, Video, iBooks, Reminders, Stocks, Settings, Voice Memos, were backed up. I then proceeded to factory reset the iPod, deleting everything and starting it as a new iPod. Once I finished this, I looked my desktop to see everything was gone, absolutely everything. I double-pressed the home button, showing Settings was open, but that's it. I opened settings and factory reset it again, this time choosing to restore from a backup. After doing this, I found the iPod looked the same as the last time i reset it - blank. If I scroll down the middle of the screen to bring up a search bar, I can find only the apps I backed up (Tips, Video, iBooks, Reminders, etc.) That is the first MAJOR problem. I was getting really frustrated, so I opened up iBooks and discovered I can download a could free books from the store, which was essentially the only thing I can use the iPod for. There were no videos in the Video app, and pressing the "Go to Store" button did absolutely nothing. No lag, it just ignored my touch. Once i found a few books, I decided to start reading. Eventually, i brought this iPod somewhere to read it, and didn't bring the charger with me. The battery died, and when i got home, tried charging it.
    Which brings me to the second problem. A minute or so after I plugged in the charger into the dead iPod, the Apple logo came on. But the iPod never started up. The logo stayed there, getting dimmer after a minute, but no vanishing even after fully charging or pulling out the charging cord. It didn't leave even after hours, but by then the battery died again. If i press and hold the power button and the home button at the same time, the Apple logo disappears. But I can't get into recovery mode utilizing the volume buttons. If i hold the power button when the screen is blank, the Apple logo comes back. But the iPod cannot start up.
    After everything was wiped, i was pretty angry. But I still had books to read, even if i couldn't do much else. Then the battery died, and it really wrecked me up. I feel so mad right now, although this actually happened about 4 days ago. The iPod being wiped happened about 3 days after the Christmas holidays began. This iPod also was not brand new, I bought it off a friend who had it for over a year, although it was in perfect condition (Obviously out of warranty.) I desperately need a solution to this HUGE problem. Due to personal reasons, I can't go to a Genius Bar or go to an Apple retailer in person, but communicating by E-mail is an option, as is instant messaging.

    Try:                                               
    - iOS: Not responding or does not turn on           
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try another cable                     
    - Try on another computer                                                       
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar
    The missing apps could have been done by setting the Restrictions that can hid those apps. If the backup was made with those retrictions set the the Restrictions are also restored.
    Thus, if you get it to work restore to factory settings/new iPod, not from backup                               
    You can redownload most iTunes purchases by:        
      Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • NIO: Strange problem when using ByteBuffer with non-blocking SocketChannel

    Hi,
    I have a server that uses multiplexed, non-blocking I/O with java.nio. When a client connects, the server waits for the message: <system cmd="knock"/>, returns a message and disconnects the client. The clients are shortly serviced in less than a second.
    But the server newer receive anything from about 20% of the clients - even though it is sent. Or with other words: it is received and the data is contained in the ByteBuffer - SocketChannel.read(ByteBuffer) - but a call to ByteBuffer.remaing() returns 0 !!
    ByteBuffer receiveBuf = ByteBuffer.allocate(65536);
    receiveBuf.clear(); // the code is elsewhere used for longer living clients
    int readBytes = channel.read(receiveBuf);
    receiveBuf.flip();
    StringBuffer sb = new StringBuffer();
    System.out.println(" * Remaining: "+receiveBuf.remaining()); // writes: ' * Remaining: 0'
    System.out.println(" * Received: "+new String(receiveBuf.array())); // writes: ' * Received: <system cmd="knock"/>'
    while(receiveBuf.remaining() >= 2) {
      byte b = receiveBuf.get();
      sb.append((char)b);
    System.out.println(" * sb content: "+sb.toString()); // writes: ' * sb content: 'The ByteBuffer clearly receives the correct data, but the ByteBuffer.remaining() returns 0 and therefore the StringBuffer will never have any content.
    The problem seems to occur randomly and for about 20% of the clients (simulated from the same computer and therefore has the same bandwidth and so on).
    Anyone knows what is going on, and how to solve the problem !?

    It's always possible in any read that the number of bytes read is less than the number of bytes requested. You need to keep reading until you have got everything you expected, and cope with every possible error condition on each iteration.
    EJP

  • My Mac just got real slow opening any webpage? My first problem, I purchased two years ago.

    I purchased my MacBook Air 13" 23 months ago and it has been awesome! My first Mac. I loaded OS X Yosemite 10.10.1 about two weeks ago without problem. I've been experiencing very slow internet downloads. I've checked all my settings and line speeds, it takes 30 to 45 seconds to bring up a page, before it was 3 to 5 seconds.  Help!

    If you have a rescue email address (which is not the same thing as an alternate email address) set up on your account then you can try going to https://appleid.apple.com/ and click 'Manage your Apple ID' on the right-hand side of that page and log into your account. Then click on 'Password and Security' on the left-hand side of that page and on the right-hand side you might see an option to send security question reset info to your rescue email address.
    If you don't have a rescue email address then see if the instructions on this user tip helps : https://discussions.apple.com/docs/DOC-4551

  • First problems with Zen

    Hi All,
    One week ago I got my Zen V plus 4GB mp3player and I was very happy with it!
    I already read that this model has a perfect sound quality, that's why I bought this player, but when I listened to it for the first time I was a bit astonished. The quality wasn't that good as I thought it would be. I'm sure the creative ear bugs have something to do with it, for sure, but I used a minidisc before this and the difference is big.
    Anyway, that's not the thing I want to tell you all. What concerns me now is the 'cracking' I hear in my music when I use the Zen V plus. With cracking I mean the 'dropouts' I hear when I cange a track (forward) or I go back (reward) to a previous song or I just pauze the song. Also while changing the preset of my EQ, everytime I change the number of a certain freq., I hear a 'dropout'. I made a little sound file, recorded from the player (I connected the headphone jack to the line in of my pc), of these cracks when I play songs on my mp3. Somewhere about 8 seconds of the sound file, you can hear it very good, when I pauze the song.
    http://users.pandora.be/Aeropolis/sample.mp3
    A second sample I made to show you the dropouts I get while changing the Equalizer presets. I chosed the song of Pink Floyd (Great gig in the sky) which has no dropouts at all. The volume of the player is 22, bassboost on. Where the bass guitar starts playing, you can hear the drops the best.
    http://users.pandora.be/Aeropolis/sample2.mp3
    How can I resolve this? Could a firmware update resolve this? If yes, then I suppose creative will have to start finding a new firmware for this player, since I already downloaded the newest version on my Zen V plus.
    I know some other people who have the same issue too.
    Thank you very much, hopefully this problem can be solved.Message Edited by Alex_R on -04-200605:36 PM
    Message Edited by Alex_R on -04-200605:36 PM

    hi,
    first of all, thank you for your reply...
    I tried other earphones, and as you can hear, on the computer (headphone jack linked with lin in) you can hear the cracks too, so I don't think the earphones are bad.
    I experimented with all the EQ freq's, also with the EQ on/off, with the bassboost on/off...it's like the headphone jack isn't connected very well inside the player.
    Anyway, I'm going to buy new headphones, maybe something changes then or I don't hear the cracks very loud because of the lone tones produced by the newer headphones.Message Edited by Alex_R on -06-20062:42 PM

  • Nio write problem: server data sent isn't fully read by client

    Hi everyone,
    still writing away with my nio server and once again have run into
    some problems. Essentially my main problem is that when the server
    writes to the client, the write appears to output all the bytes in the
    write operation, but the client never accepts them all, even if a
    buffer has been manually allocated to the correct size of the data.
    As background my server will accept connections. When a connection
    is established I register OP_READ on the key. When a OP_READ trigger
    occurs the server accepts the clients request, processes it, then
    attaches the output to the SelectionKey as a ByteBuffer that has
    already been encoded. At this point I then register OP_WRITE on that
    SelectionKey (as a side note i'm running this server on XP and had
    read that registering OP_READ and OP_WRITE on the same selector was
    bad, but then it looked like there was a work around to this) and wait
    for an OP_WRITE trigger.
    When an OP_WRITE occurs on that key I run a new method (with heavy
    influences from the thread: http://forum.java.sun.com/thread.jsp?forum=11&thread=530825 and the taming the nio circus thread) which will grab the attachment and attempt to send it. The code has been written that IF the send cannot complete it should re-attach the remaining bytebuffer to the key and wait for another OP_WRITE to occur so it can send the remainder.
    The problem is that whenever I write (and for this test the amount im writing is approx 10100 bytes) the server appears to send it all (by checking the int returned from socketchannel.write()), but at the client end it never reads all the data that is sent.
    If i'm using a blocking socket client, then I get a java.net.SocketException: Connection Reset exception, whilst if i'm using a non-blocking client, I get no exception, just not the whole amount of data, even when i've statically allocated a receiving bytebuffer that is big enough.
    The following code is a class that is used to do the writing from the server:
       /* code for nio write model referenced from:
         * http://forum.java.sun.com/thread.jsp?forum=11&thread=530825
        class NIOWriteHandler {
            private ByteBuffer sendBuffer;
            private SelectionKey localSelectionKey;
            NIOWriteHandler(SelectionKey currentKey) {
                localSelectionKey = currentKey;
            public void doWrite() {
                localSelectionKey.interestOps(SelectionKey.OP_READ);  //deselect write,
                sendBuffer = (ByteBuffer)localSelectionKey.attachment();
                // perform the writing
                SocketChannel writingChannel = (SocketChannel)localSelectionKey.channel();
                if (writingChannel.isOpen()) {
                    int len = 0;
                    if (sendBuffer.hasRemaining()) {
                        try {
                            System.out.println("Sending chunks o data");
                            len = writingChannel.write(sendBuffer);
                            System.out.println("value of len: " + len);
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                            // call close method
                            System.out.println("CLOSE INVOKED at POINT 8");
                            closeComplete(localSelectionKey);
                    System.out.println("Second IF coming...");
                    if (sendBuffer.hasRemaining()) {
                        // if we get here then the previous write did not fully
                        // complete, so need to save data etc
                        System.out.println("Couldn't send all data this time...");
                        localSelectionKey.interestOps(SelectionKey.OP_WRITE|SelectionKey.OP_READ);
                        localSelectionKey.attach(sendBuffer);
                    } else {
                        sendBuffer = null;
                        closeComplete(localSelectionKey);
                // write complete at this stage
        }This is the basic block client that is incredibly dumb:
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.*;
    import java.nio.ByteBuffer;
    public class ServerTest {
        /* args 0 - the IP of the machine to connect to
           args 1 - the port number
           Simple client that connects to a specified IP & port, takes a line
           of input via stdin, sends that to the connected machine and prints
           out the response.
           Error handling and such isn't accounted for.
       public static void main (String args[]) throws Exception{
            Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
            BufferedReader buffRead = new
                BufferedReader(new InputStreamReader((socket.getInputStream())));
            PrintStream ps =
                new PrintStream(socket.getOutputStream());
            Charset charset = Charset.forName("ISO-8859-1");
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("[CLIENT]Data to send: ");
            String data = stdin.readLine();
            ps.println(data);
            String returned = buffRead.readLine();
            while (returned != null) {
                System.out.println(returned);
                returned = buffRead.readLine();
            System.out.println("[CLIENT]End server response");
            buffRead.close();
            ps.close();
            socket.close();
    }And here is the non-blocking basic client (which dosn't actually close at the moment):
    import java.net.*;
    import java.util.*;
    import java.io.*;
    import java.nio.charset.*;
    import java.nio.channels.*;
    import java.nio.*;
    public class ServerTestNonBlock {
        /* args 0 - the IP of the machine to connect to
           args 1 - the port number
           Simple client that connects to a specified IP & port, takes a line
           of input via stdin, sends that to the connected machine and prints
           out the response.
           Error handling and such isn't accounted for.
       public static void main (String args[]) throws Exception{
            InetSocketAddress addr = new InetSocketAddress
                (args[0], Integer.parseInt(args[1]));
            SocketChannel sc = SocketChannel.open();
            sc.configureBlocking(false);
            Selector selector = Selector.open();
            System.out.println("Starting connection...");
            sc.connect(addr);
            while(!sc.finishConnect()) {
               System.out.println("1,2,3,4 I will keep on counting...");
            System.out.println("Connection established..");       
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();
            sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            while (true) {
               int n = selector.select();
               if (n==0) {
                  continue;
               Set keys = selector.selectedKeys();
               Iterator it = keys.iterator();
               while (it.hasNext()) {
                  SelectionKey selKey = (SelectionKey)it.next();
                  if (selKey.isReadable()) {
                     // time to setup read
                     ByteBuffer incomingData =
                        ByteBuffer.allocateDirect(102000);
                     incomingData.clear();
                     int count;
                     while ((count = sc.read(incomingData)) > 0) {
                        System.out.println("Value of count: " + count);
                        // reading the data
                     System.out.println("Count value: " + count);       
                     int pos = incomingData.position();
                     incomingData.flip();
                     CharBuffer content = charset.decode(incomingData);
                     String inData = content.toString();
                     System.out.println(inData.trim());
                     System.out.println("[CLIENT]End server response");
                     System.out.println("Count value: " + count);       
                     System.out.println("Position value: " + pos);       
                     //sc.close();
                     //break;
                  if (selKey.isWritable()) {
                     BufferedReader stdin = new BufferedReader
                       (new InputStreamReader(System.in));
                     System.out.println("[CLIENT]Data to send: ");
                     String data = stdin.readLine();
                     ByteBuffer byteBufferOut = encoder.encode
                        (CharBuffer.wrap(data));
                     int length = sc.write(byteBufferOut);
                     System.out.println("Wrote: " + length + " bytes.");
                     selKey.interestOps(SelectionKey.OP_READ);
    }I'm kinda stuck at the moment and am making change for the sake of change without getting a good grasp of what is going on. If anyone can provide any help that'd be fantastic. If in the mean time I figgure something out i'll post a response.
    If you've gotten this far thanks a bunch for reading :)
    Cheers,
    Pete

    Hi Meesum,
    thanks for the reply :)
    I'm not convinced this is the error - as i've got two clients listed there, and the odd behaviour from both is that neither is getting through to the last of the data that is sent.
    If the null were the problem (which is only checked for in the basic dumb blocking client) i'd be expecting some sort of infinite loop or wait for more data from the server, not an abnormal termination (ala connection reset) from the server. I'll give it a shot anyhow, but I know that under a blocking write operation that that code worked fine.
    Thanks again though for the post, has got some of my cogs slowly turning :)
    Cheers,
    Pete

  • First problem with Streams

    Hi,
    this is my first time using Streams so perhaps my questions are stupid ... I have a two node RAC in 10.2.0.4 with all patches needed for using Oracle Streams (10.2.0.4.4 to be more exact). This RAC has some tables from which i need to replicate a few columns. Mi first aproach has been using the following code to test a little example from a table with three columns and removing from lcr two of them.
    create or replace function removecolumns (inAnyData in SYS.AnyData)
    RETURN SYS.AnyData IS
    ret pls_integer;
    typelcr VARCHAR2(61);
    lcrOut SYS.LCR$_ROW_RECORD;
    v_col3_old_anydata SYS.AnyData;
    v_col3_new_anydata SYS.AnyData;
    v_col3_old_str varchar2(512);
    v_col3_new_str varchar2(512);
    BEGIN
    typelcr := inAnyData.getTypeName();
    IF typelcr = 'SYS.LCR$_ROW_RECORD' THEN
    ret := inAnyData.GetObject(lcrOut);
    IF lcrOut.get_object_owner() = 'SCOTT' THEN
    IF lcrOut.get_object_name() = 'T6' THEN lcrout.
    lcrout.delete_column('COL2','*');
    lcrout.delete_column('COL3','*');
    RETURN SYS.AnyData.ConvertObject(lcrOut);
    END IF;
    END IF;
    end if;
    RETURN inAnyData;
    END;
    This first replication has been for the whole schema (this is my first test ...). The problem appears when I try a dml. The error in the alert log from the node in which I am connected is:
    LOGMINER: Begin mining logfile for session 1 thread 2 sequence 22, +DATA/probid/onlinelog/group_4.266.735925225
    Thu Dec 2 17:51:21 2010
    Errors in file /u01/app/oracle/product/10.2.0/db_1/admin/probid/bdump/probid1_c001_4950.trc:
    ORA-23607: invalid column "COL2"
    ORA-06512: at "SYS.LCR$_ROW_RECORD", line 325
    ORA-06512: at "STRMADMIN.REMOVECOLUMNS", line 21
    ORA-06512: at line 1
    Thu Dec 2 17:51:24 2010
    Streams CAPTURE C001 with pid=32, OS id=4950 stopped
    Thu Dec 2 17:51:24 2010
    Errors in file /u01/app/oracle/product/10.2.0/db_1/admin/probid/bdump/probid1_c001_4950.trc:
    ORA-23607: invalid column "COL3"
    ORA-06512: at "SYS.LCR$_ROW_RECORD", line 325
    ORA-06512: at "STRMADMIN.REMOVECOLUMNS", line 21
    ORA-06512: at line 1
    The most extrange is that the update works fine until I do create the column COL3 on source (and col2 already did exist) , it then is replicated to target. From target database I do remove the column COL3 and try and insert, this is the momento in which the error appears.
    I have two questions,
    - Any suggest for this error?
    - How should I focus this replication with a set of tables and only a few columns in the target?. I have used only one process for capture-replicate-apply and I think I dno not need more. If it is possible I wouldn´t like to use dbms_streams_adm nor apply dml handler to solve the problem...
    Tks.
    Edited by: user12046001 on 02-dic-2010 13:17

    Thank you !,
    however the error still appears where I try an update or delete operation:
    Fri Dec 3 11:52:52 2010
    Errors in file /u01/app/oracle/product/10.2.0/db_1/admin/probid/bdump/probid1_c001_8434.trc:
    ORA-23607: invalid column "C"
    ORA-06512: at "SYS.LCR$_ROW_RECORD", line 325
    ORA-06512: at "STRMADMIN.REMOVECOLUMN", line 17
    ORA-06512: at line 1
    Fri Dec 3 11:52:55 2010
    Streams CAPTURE C001 with pid=37, OS id=8434 stopped
    Fri Dec 3 11:52:55 2010
    Errors in file /u01/app/oracle/product/10.2.0/db_1/admin/probid/bdump/probid1_c001_8434.trc:
    ORA-23607: invalid column "C"
    ORA-06512: at "SYS.LCR$_ROW_RECORD", line 325
    ORA-06512: at "STRMADMIN.REMOVECOLUMN", line 17
    ORA-06512: at line 1
    By now, this is the code used (really it´s yours ...):
    create or replace function borrar( inAnyData in SYS.AnyData)
    RETURN SYS.AnyData IS
    ret pls_integer;
    typelcr VARCHAR2(61);
    lcrOut SYS.LCR$_ROW_RECORD;
    BEGIN
    typelcr := inAnyData.getTypeName();
    IF typelcr = 'SYS.LCR$_ROW_RECORD' THEN
    -- Typecast AnyData to LCR$_ROW_RECORD
    ret := inAnyData.GetObject(lcrOut);
    IF lcrOut.get_object_owner() = 'SCOTT' THEN
    IF lcrOut.get_object_name() = 'T6' THEN
    lcrOut.delete_column(column_name=>'C');
    lcrOut.delete_column(column_name=>'NUEVA');
    RETURN SYS.AnyData.ConvertObject(lcrOut);
    END IF;
    END IF;
    END IF;
    -- if we are here then the LCR is not a row
    -- or the row was not one bound for transformation,
    -- so we alter nothing
    RETURN inAnyData;
    END;
    declare
    action_ctx sys.re$nv_list;
    ac_name varchar2(30) := 'STREAMS$_TRANSFORM_FUNCTION';
    BEGIN
    action_ctx := sys.re$nv_list(sys.re$nv_array());
    action_ctx.add_pair( ac_name, sys.anydata.convertvarchar2('strmadmin.REMOVECOLUMN'));
    dbms_rule_adm.alter_rule( rule_name => 'SCOTT1',
    action_context => action_ctx);
    end ;
    SQL> select rule_set_name from dba_capture;
    RULE_SET_NAME
    RULESET$_3
    SQL> select rule_name from dba_rule_set_rules r where r.RULE_SET_NAME='RULESET$_3';
    RULE_NAME
    SCOTT1
    SCOTT2
    select rule_name,RULE_CONDITION from dba_rules where rule_name in ('SCOTT1','SCOTT2');
    Rule Name Rule Condition
    SCOTT1 ((:dml.get_object_owner() = 'SCOTT') and :dml.is_null_tag() = 'Y' and :dml.get_source_database_name() = 'PROBID' )
    SCOTT2 ((:ddl.get_object_owner() = 'SCOTT' or :ddl.get_base_table_owner() = 'SCOTT') and :ddl.is_null_tag() = 'Y' and:ddl.get_source_database_name() = 'PROBID' )
    Sincerely, I can´t understand where is the error. Thank you for your help :)

  • How to feed CharsetDecoder (nio Buffer problems)

    Hi there,
    I have no idea how to feed bytes into a CharsetDecoder in presence of multibyte sequences. I am trying something along the following lines.
    If a multibyte char is being fed (I tried c3 +a4 = �), the first call to decode returns UNDERFLOW with bout.hasRemaining() == false as expected, but the 2nd call yields MALFORMED[1], no matter what rewind/flip method I throw in at // *1*
    I probably "misgrok" something here with Buffers. Can someone point out what?
      ByteBuffer bin = ByteBuffer.allocate(3);
      CharBuffer bout = CharBuffer.allocate(1);
      Charset cs = Charset.forName("UTF-8");
      CharsetDecoder dec = cs.newDecoder();
      public void addChar( int ch ) throws Exception {
        bin.put((byte)ch);
        bin.flip();
        CoderResult res = dec.decode(bin,bout,false);
        bout.flip();
        if( bout.hasRemaining() ) {
          emit( bout.get() );
          bin.clear();
          bout.clear();
        } else {
          bout.flip();
          //bin.flip(); // *1*
      }

    But the result character is already in the output buffer?! Applying my program code to ISO-8859-1, all character yield underflows and the data is successfully being converted.
    Here is a complete test program:
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;
    public class DecoderTest {
      public static void main( String[] args ) throws Exception {
        dec = Charset.forName(args[1]).newDecoder();
        new DecoderTest().run(args[0]);
      ByteBuffer bin = ByteBuffer.allocate(3);
      CharBuffer bout = CharBuffer.allocate(1);
      static CharsetDecoder dec;
      public void run( String filename ) throws Exception {
        FileInputStream in = new FileInputStream(filename);
        int ch;
        while( (ch=in.read())>=0 ) {
          addChar(ch);
      public void addChar( int ch ) throws Exception {
        System.out.print( "byte "+(0xff & ch) + " => " );
        bin.put((byte)ch);
        bin.flip();
        CoderResult res = dec.decode(bin,bout,false);
        System.out.print( res + " => " );
        if( res.isError() ) {
          bin.clear();
          bout.clear();
        } else {
          bout.flip();
          if( bout.hasRemaining() ) {
            System.err.print( "char " + ((int)bout.get()) );
            bin.clear();
            bout.clear();
          } else {
            bout.flip();
           // what to do with bin here???
        System.err.println();
    }Passing in iso latin code lopoks like this:
    byte 98 => UNDERFLOW => char 98
    byte 228 => UNDERFLOW => char 228
    byte 104 => UNDERFLOW => char 104
    byte 32 => UNDERFLOW => char 32
    byte 98 => UNDERFLOW => char 98
    byte 228 => UNDERFLOW => char 228
    byte 104 => UNDERFLOW => char 104
    byte 10 => UNDERFLOW => char 10Utf-code looks like this:
    byte 98 => UNDERFLOW => char 98
    byte 195 => UNDERFLOW =>
    byte 164 => MALFORMED[1] =>
    byte 104 => UNDERFLOW => char 104
    byte 32 => UNDERFLOW => char 32
    byte 98 => UNDERFLOW => char 98
    byte 195 => UNDERFLOW =>
    byte 164 => MALFORMED[1] =>
    byte 104 => UNDERFLOW => char 104
    byte 10 => UNDERFLOW => char 10Message was edited by:
    HolgerK

  • 6714 init PCI display first problem

    I have a MSI 6714 V1 mainboard, that has integrated graphics. Now i want to install a PCI graphics card with TV-out, but no matter how i adjust the BIOS settings, the computer does not want to use the PCI-card. I have tried to disable the onboard graphics card and enable init PCI display first, but it does not work. I have read that others have had the same problem with this mainboard. I have the newest BIOS version and there is nothing wrong with the PCI card. (Powercolor 9200SE PCI).
    Any hints?

    Quote
    Originally posted by Lightyear
    I have a MSI 6714 V1 mainboard, that has integrated graphics. Now i want to install a PCI graphics card with TV-out, but no matter how i adjust the BIOS settings, the computer does not want to use the PCI-card. I have tried to disable the onboard graphics card and enable init PCI display first, but it does not work. I have read that others have had the same problem with this mainboard. I have the newest BIOS version and there is nothing wrong with the PCI card. (Powercolor 9200SE PCI).
    Any hints?
    Well I dont really know... I was just thinking maybe you should read ur manual... Because some motherboards have PCI ports that are previewed for certain PCI cards...
    For example: I had a friend.. he couldnt get his soundcard working so then i told him to read his MB manual.. and in the manual it said: "for sound cards use PCI slot 2"... or something like that....  And it worked for him...
    I dont know why they do that... I think it has to do with the IRQ's...  
    As i said.. its just an Idea.. I dont know your motherboard...
    sorry
    greez Steph  
    good luck

  • Newcomer - Hello - my first problem....

    I have my first blackberry. A curve 8520 v5.0.0.681. with Virgin Mobile.
    I seemed to have managed to connect to my wi-fi home network as i have the relevant icons on the home screen.
    But for some mad reason windows 7 on my laptop does not find or 'discover' my blackberry when I come to add a device. I realize this is probably more a windows problem but i have had no success in windows forums...hoping for help here at Blackberry ?

    Greetings, and welcome to the BlackBerry.com Community Support Forums.
    Have you installed the BlackBerry Desktop Software to the laptop?
    Can you try using a different USB port on the laptop?
    Article ID: KB00125 Identifying and troubleshooting issues with the BlackBerry Desktop Software detecting a USB connected BlackBerry smartphone
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • Keychain -- first problem

    I restarted my MacBook Air (latest version & 10.9.1) for the first time in a week (had been putting in sleep mode when not using) and am suddenly getting boxes asking for a password so that CalendarAgent, com.apple.internetaccounts.xpc, MenuCalendarClock iCal, Messages Agent, etc. can use the "login" keychain -- or "Local Items."  I can't get past these boxes.
    Frankly, I don't remember ever setting up a password for Keychain in past years, and I have never been asked for one like this before.  Passwords I've tried don't work.
    I have a 2 month old clone that I could pull a file from, but I think Mavericks hides this stuff nowadays. I could also just clone it back -- probably the best idea.
    Having had many Macs over the years, I have never run into this problem before!!

    Well, I moved my SuperDuper clone back to the MacBook Air and all is well.  The password that wouldn't work in Keychain was the right password because it works now. 
    Apparently, somehow Keychain got corrupted, but I have no idea how that happened -- never have seen the problem before and hope I never see it again.

  • Contract renewal and first  problem  VERIZON WIRELESS..." WORRY FREE" IS NOT FREE WATCH

    i JUST RENEWED MY CONTRACT ONCE MORE , AS i HAVE DONE PLENTY OF TIMES IN THE PAST , BUT THIS TIME THE PHONE i PICKED , WELL THE EXILUIM WORKED FINE FOR ABOUT ONE WEEK , BUT THEN I REALIZED IT WOULD NOT HOLD A CHARGE !, now by this time ( being with Verizon as long as I have and not having had any problems ) I had thrown the box away that the phnoe came in , well now they will not take it back because the box is gone, and they will not send me AT THE LEAST ANOTHER BATTERY FOR MY BOULDER . I cannot get anyone to help me ( a good paying customer with two active phones, ) but I will leave VERIZON AS SOON AS POSSIBLE, the way I see it they have but one chance to keep my business and that is to honor the " worry free " thing they so boast on.

    mccahill wrote:
    i JUST RENEWED MY CONTRACT ONCE MORE , AS i HAVE DONE PLENTY OF TIMES IN THE PAST , BUT THIS TIME THE PHONE i PICKED , WELL THE EXILUIM WORKED FINE FOR ABOUT ONE WEEK , BUT THEN I REALIZED IT WOULD NOT HOLD A CHARGE !, now by this time ( being with Verizon as long as I have and not having had any problems ) I had thrown the box away that the phnoe came in , Being with Verizon as long as you have, you would (SHOULD) also be aware of the policy that the phone needs to be returned IN THE ORIGINAL PACKAGING....I ALWAYS save everything until I am beyond the return point....I know I can return it, but I also know I need the packaging and the UPC to get any mail in rebates--so I don't even cut out the UPC until I know I'm going to keep the phone. 
    well now they will not take it back because the box is gone, Ummmm, yeah, that's what the rules are... and they will not send me AT THE LEAST ANOTHER BATTERY FOR MY BOULDER If it's your old phone, then it's on you--I replace batteries and don't expect Verizon to pay...there are lots of accessory vendors on line with awesome prices; just be sure to get an OEM battery.  I've had good service, fast delivery, and excellent products buying online. 
    I cannot get anyone to help me ( a good paying customer with two active phones, ) but I will leave VERIZON AS SOON AS POSSIBLE, the way I see it they have but one chance to keep my business and that is to honor the " worry free " thing they so boast on.  You have (had) a responsibility as well; there are conditions for returning and exchanging phones via the Worry Free Guarantee, and you don't have the original packaging.  You can keep trying, and you may eventually get a sympathetic rep.  Good luck.

  • First problem since 2009 - Yosemite

    Problem description:
    I have a fairly old macbook pro, purchased in 2009.  Never had any problems with it but since upgrading to yosemite it takes minutes to boot up, before the download it was seconds.  Also the spinning ball of death shows up at least once for every thing I try to do.  I’m not very Mac savvy, so I don’t know what to do.  I have used it since 09 for school and at home but never had to do anything technical.  Any help would be appreciated!!
    EtreCheck version: 2.1.6 (109)
    Report generated January 24, 2015 at 1:42:00 AM CST
    Download EtreCheck from http://etresoft.com/etrecheck
    Click the [Support] links for help with non-Apple products.
    Click the [Details] links for more information about that line.
    Click the [Adware] links for help removing adware.
    Hardware Information: ℹ️
      MacBook Pro (13-inch, Mid 2009) (Technical Specifications)
      MacBook Pro - model: MacBookPro5,5
      1 2.26 GHz Intel Core 2 Duo CPU: 2-core
      2 GB RAM Upgradeable
      BANK 0/DIMM0
      1 GB DDR3 1067 MHz ok
      BANK 1/DIMM0
      1 GB DDR3 1067 MHz ok
      Bluetooth: Old - Handoff/Airdrop2 not supported
      Wireless:  en1: 802.11 a/b/g/n
      Battery Health: Normal - Cycle count 334
    Video Information: ℹ️
      NVIDIA GeForce 9400M - VRAM: 256 MB
      Color LCD 1280 x 800
    System Software: ℹ️
      OS X 10.10 (14A389) - Time since boot: 0:51:39
    Disk Information: ℹ️
      Hitachi HTS545016B9SA02 disk0 : (160.04 GB)
      EFI (disk0s1) <not mounted> : 210 MB
      Macintosh HD (disk0s2) / : 159.18 GB (75.90 GB free)
      Recovery HD (disk0s3) <not mounted>  [Recovery]: 650 MB
      HL-DT-ST DVDRW  GS23N 
    USB Information: ℹ️
      Apple Inc. Built-in iSight
      Apple Internal Memory Card Reader
      Apple Computer, Inc. IR Receiver
      Apple Inc. Apple Internal Keyboard / Trackpad
      Apple Inc. BRCM2046 Hub
      Apple Inc. Bluetooth USB Host Controller
    Gatekeeper: ℹ️
      Mac App Store and identified developers
    Launch Daemons: ℹ️
      [loaded] com.adobe.fpsaud.plist [Support]
      [loaded] com.microsoft.office.licensing.helper.plist [Support]
    User Launch Agents: ℹ️
      [loaded] com.google.keystone.agent.plist [Support]
    User Login Items: ℹ️
      iTunesHelper Application  (/Applications/iTunes.app/Contents/MacOS/iTunesHelper.app)
      Safari Application  (/Applications/Safari.app)
      Google Drive Application  (/Applications/Google Drive.app)
      Google Chrome Application Hidden (/Applications/Google Chrome.app)
    Internet Plug-ins: ℹ️
      SharePointBrowserPlugin: Version: 14.4.7 - SDK 10.6 [Support]
      FlashPlayer-10.6: Version: 16.0.0.287 - SDK 10.6 [Support]
      Flash Player: Version: 16.0.0.287 - SDK 10.6 [Support]
      QuickTime Plugin: Version: 7.7.3
      Default Browser: Version: 600 - SDK 10.10
    3rd Party Preference Panes: ℹ️
      Flash Player  [Support]
    Time Machine: ℹ️
      Auto backup: YES
      Volumes being backed up:
      Macintosh HD: Disk size: 159.18 GB Disk used: 83.28 GB
      Destinations:
      Stephy's External Drive [Local]
      Total size: 999.86 GB
      Total number of backups: 1
      Oldest backup: 2014-10-10 23:44:47 +0000
      Last backup: 2014-10-10 23:44:47 +0000
      Size of backup disk: Excellent
      Backup size 999.86 GB > (Disk size 159.18 GB X 3)
    Top Processes by CPU: ℹ️
          7% WindowServer
          1% Google Chrome
          0% Google Drive
          0% AppleSpell
          0% askpermissiond
    Top Processes by Memory: ℹ️
      146 MB Google Chrome
      76 MB Google Chrome Helper
      43 MB Finder
      34 MB WindowServer
      26 MB mds
    Virtual Memory Information: ℹ️
      34 MB Free RAM
      652 MB Active RAM
      637 MB Inactive RAM
      362 MB Wired RAM
      2.39 GB Page-ins
      84 MB Page-outs
    Diagnostics Information: ℹ️
      Jan 24, 2015, 12:51:03 AM Self test - passed

    While Apple says 2 GB of RAM is required the consensus seems to be at least 4 GB is needed for a smooth operating OS. More than 4 GB is better.
    The 2 places I’ve seen recommended most to buy reliable RAM are below. I have purchased RAM several times from Other World Computing and have always been very satisfied with the product and service. They have on-line instructions on how to replace the RAM. OWC has also tested RAM above what Apple states is the maximum. I now have 6GB installed on a machine supposedly limited to 4 GB.
    Crucial
    Other World Computing

  • "error 3194 and have tried all recommended steps, first problem with this iphone"

    Hi, for a few months now I've been using my brother's old iPhone 3GS as an iPod, and I haven't jailbreaken it or anything of the sort, and I've installed every update since, and today I installed the newest update and since it has been in recovery mode and whenever I connect it to iTunes and try to restore (I backed up a few days ago) I am greeted with an iTunes message saying "error 3194" and I've tried everything mentioned in the specific update article for it except for the one pertaining to a .ipsw because when I go to advanced settings I am unable to find anything of the sort. And it'd be much appreciated if any of you could help! Also, I am using a windows computer, not a mac, and have never had problems with this iPhone until this new update.

    It is usually given as a communication error between Apple, iTunes (your computer), iPhone. Somewhere they are not communicating, so the iOS you are trying to install cannot be approved by Apple. Trouble shooting steps include, making sure you have Current iTunes installed, make sure your Hosts file of computer is not blocking Apple. Try restoring on another computer.

Maybe you are looking for