NIO sockets - cant get it to block!

Hi,
I'm trying to use NIO sockets in a program which sends data to a socket on another machine. I want it to block so that it must wait for a response before it continues. However this doesnt happen! I used Ethereal to see the packets being sent and recieved and the socket clearly doesnt block. Am I correct in thinking that NIO sockets are configured to block by default? I even tried using the configureBlocking(true) method to make sure but it still didnt block. Can anyone shed some light onto why this could be happening? Has this happened to anyone else?
Cheers

thomfost wrote:
I've tried using regular I/O but its a bit too slow for what I need, im trying to see if using NIO improves this.Well you can stop now because it won't. NIO, as mentioned, is non-blocking IO, so a thread that is titled "NIO sockets - cant get it to block!" is not ultra promising. More importantly NIO will not make your IO "faster" by some magic. That's not what it does. It helps you write programs that scale because you don't need to have a thread dedicated to every client who connects to your system.
At any rate you have multiple mistakes here which suggest the other slowness problem you refer to is a logical problem in your code. So why don't you tell us about that instead?

Similar Messages

  • Very big icons on my screen.  Have turned off and on.  Cant get rid off.  Cant downsize screen to enter my pin.  Sems blocked or stalled.  What to do?

    Very big icons on my screen.  Have turned off and on.  Cant get rid off.  Cant downsize screen to enter my pin.  Sems blocked or stalled.  What to do?

    Double tap with THREE fingers to turn zoom off. Then go into Settings>General>Accessibility and turn zoom off for good.

  • Hey I would like to get app to block unwanted calls but cant find. any advise

    hey I would like to get app to block unwanted calls but cant find. any advise

    Yup, dito to ckuan's response - Contact your carrier or assign a silent ringtone/message tone to the contact so you will not be alerted at all to the calls/messages.

  • How can i get the ipad to work because my little brother put a password on it and it now is blocked and cant get into it ???

    how can i get my ipad to work because ,y little brother put a password and cant get into it ???

    You must restore the iPad with iTunes.

  • NIO sockets

    Hello,
    Im having difficulty understanding the WRITE issue of nio sockets. Ive read most of the nio-related posts on this forum but I still cant figure it out. Ive also looked at some examples by PkWooster but they seems really complicated.
    I have a server which accepts connections and echos messages to all clients. Everything works fine except my client cannot write to the server. I know I need to switch back and forth between Op interests since they can block the cpu if set incorrectly but I dont really understand what to set when. Since my server seems to be working fine Ill post my Clients code:
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.net.InetSocketAddress;
    import java.util.*;
    import java.nio.charset.*;
    public class GameClient implements Runnable {
      Game game;
      SocketChannel sc;
      ByteBuffer buffer;
    Selector selector;
    ByteBuffer sendBuffer=null;
        String host = "192.168.1.102";
        int port = 8888;
    private CharsetDecoder asciiDecoder;
    private CharsetEncoder encoder;
    private LinkedList sendQ = new LinkedList();
    SelectionKey sk;
    LinkedList invocations;
    public GameClient (Game g) {
    game = g;
        buffer = ByteBuffer.allocateDirect(1024);
              Charset charset = Charset.forName("ISO-8859-1");
              asciiDecoder = charset.newDecoder();
              encoder = charset.newEncoder();
    game.CharMSGArrival("Starting...");  // transfers data to the game thread
    public void run(){
    try{
        // Create a nonblocking socket channel and connect to server.
        sc = SocketChannel.open();
        sc.configureBlocking(false);
    game.CharMSGArrival("Connecting to server..."+"\n");
        InetSocketAddress addr = new InetSocketAddress(host, port);
        sc.connect(addr);    // Nonblocking
        while (!sc.finishConnect()) {
    game.CharMSGArrival("I am waiting ..."+"\n" );
    game.CharMSGArrival("Connection acqired"+ "\n" );
        // Send initial message to server.
        buffer.put((new Date().toString()+ "\n").getBytes());
        buffer.flip();
        sc.write(buffer);
        // Create a new selector for use.
        selector = Selector.open();
        // Register the socket channel with the selector.
        sk = sc.register(selector, SelectionKey.OP_READ);
        while (true) {
            //System.out.println("Listening for server on port " +
             //                   remotePort);
            // Monitor the registered channel.
            int n = selector.select();
            if (n == 0) {
                continue;   // Continue to loop if no I/O activity.
            // Get an iterator over the set of selected keys.
            Iterator it = selector.selectedKeys().iterator();
            // Look at each key in the selected set.
            while (it.hasNext()) {
                // Get key from the selected set.
                SelectionKey key = (SelectionKey) it.next();
                // Remove key from selected set.
                it.remove();
                // Get the socket channel from the key.
                SocketChannel keyChannel = (SocketChannel) key.channel();
                // Is there data to read on this channel?
                if (key.isReadable()) {
                    replyServer(keyChannel);
                if (key.isWritable()) {
                    doSend();
           } catch (IOException ioe) {
      private void replyServer(SocketChannel socketChannel)
                          throws IOException {
        // Read from server.
    buffer.flip( );
        int count = socketChannel.read(buffer);
        if (count <= 0) {
            // Close channel on EOF or if there is no data,
            // which also invalidates the key.
            socketChannel.close();
            return;
    buffer.flip( );
    String str = asciiDecoder.decode(buffer).toString( );
         game.CharMSGArrival(str);
    public void doSend(){
    sk.interestOps(SelectionKey.OP_WRITE);     
    if(sendBuffer != null)write(sendBuffer);
    writeQueued();     
    public void trySend(String text){ // this method is invoked when a send buttong is pressed in the 'game' thread
              sendQ.add(text);     // first put it on the queue
              writeQueued();          // write all we can from the queue
         private void writeQueued()
              while(sendQ.size() > 0)     // now process the queue
                   String msg = (String)sendQ.remove(0);
                   write(msg);     // write the string
    private void write(String text)
              try
              ByteBuffer buf = encoder.encode(CharBuffer.wrap(text));
                   write(buf);
              catch(Exception e){e.printStackTrace();}
             * write out a byte buffer
         private void write(ByteBuffer data)
              SocketChannel scc = (SocketChannel)sk.channel();
              if(scc.isOpen())
                   int len=0;
                   if(data.hasRemaining())
                        try{len = sc.write(data);}
                        catch(IOException e){e.printStackTrace(); //closeComplete();
                   if(data.hasRemaining())     // write would have blocked
    game.CharMSGArrival("write blocked"+"/n");
                        //writeReady = false;
         sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);     // select OP_WRITE
                        sendBuffer = data;          // save the partial buffer
                   else {sendBuffer = null;
    sk.interestOps(SelectionKey.OP_READ);     }
              else game.CharMSGArrival("write closed"+"/n");
    }

    public void doSend(){
    sk.interestOps(SelectionKey.OP_WRITE);     
    if(sendBuffer != null)write(sendBuffer);
    writeQueued();     
    }This method makes no sense. You only get into it if the key is writable, which means it is already registered for OP_WRITE, so why would you register it again?
    Also you're frequently ignoring the result of many write calls, of which you have too many.
    See the thread 'Taming the NIO circus': http://forum.java.sun.com/thread.jspa?threadID=459338,
    ignoring all the contributions except those by pkwooster and me.
    I'm not that crazy about Mina myself. It has its own buffer classes and it quietly uses threads, i.e. missing the entire point of NIO.

  • I cant get two monitors to work on one pc.

    Does anyone know why i cant get two monitors working on one pc?
    I have a HP P6 2000 UKM computer, running windows 7 and it has a DVI D socket as well as the standard VGA (which i am using for my primary monitor)  I have got the right DVI  to VGA adaptor and have followed various instructions to set up duel disply but every tutorial i have seen says use the multiple display option,  but the option dropdown box is not there!
    Iv'e tried two different monitors but he same problem. If my graphics card does not suport 2 monitors then why is there a DVI D socket?
    Have never had this problem in the past!
    Please help.
    Nobby

    Hi,
    Please post the exact HP product number for your PC.
    VGA is analog and DVI-D is digital.  If you have two monitors then one of them needs to support a digital video signal if you want to use two monitors
    HP DV9700, t9300, Nvidia 8600, 4GB, Crucial C300 128GB SSD
    HP Photosmart Premium C309G, HP Photosmart 6520
    HP Touchpad, HP Chromebook 11
    Custom i7-4770k,Z-87, 8GB, Vertex 3 SSD, Samsung EVO SSD, Corsair HX650,GTX 760
    Custom i7-4790k,Z-97, 16GB, Vertex 3 SSD, Plextor M.2 SSD, Samsung EVO SSD, Corsair HX650, GTX 660TI
    Windows 7/8 UEFI/Legacy mode, MBR/GPT

  • I cant get live update to work

    I have service pack 2 installed and I cant get on live update because it just dosent load any options at the side bar.  What do I do?
    Thanks for any help

    do u not see the yellow line below the address bar see attached:-
    Live Update SP2
    if so follow:
    Quote
    it says click on here 4 more options
    so click allow blocked options
    select yes in clickbox
    there they are  
    if all else fails i suggest u uninstall live update
    go to MSI Utility Downloads
    and d/load the latest version v3.62 d.17/09/04
    which u can then install.
    when u run this u should see the screen as above pic

  • I cant get my sound to work

    I have the MSI K8M Neo-V Socket 754 VIA K8M800 ATX AMD Motherboard. I cant get the onboard audio to work. I've downloaded and ran necessary drivers and still pc can not find an output sound device anyone have any ideas

    Hai Guys,
                    My Machine Configuration is
                                     K8M Neo-V V Class mother board
                                     AMD 64
                                     Windows XP-SP2
                     The problem is i am unable to get 6 channel audio in WIndows. But it is working in LINUX. What is the problem? I enabled the advanced settings from Control panel. I enabld 5.1 surround system from SOUND EFFECT COntrol panel. even though i can't get the sound. Please give me the solution.
                                                                                                                                     Pradeep Viswamitra

  • ANOTHER Java NIO Socket Bug??

    I think I'm being really dense here but for the life of me, I can't get this code to work properly. I am trying to build a NIO socket server using JDK 1.4.1-b21. I know about how the selector OP_WRITE functionality has changed and that isn't my problem. My problem is that when I run this code:
    if (key.isAcceptable()) {
         System.out.println("accept at " + System.currentTimeMillis());
         socket = server.accept();
         socket.configureBlocking(false);
         socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    if (key.isWritable()) {
         SocketChannel client = (SocketChannel)key.channel();
         System.out.println("write at " + System.currentTimeMillis());
    if (key.isReadable()) {
         SocketChannel client = (SocketChannel)key.channel();
         readBuffer.clear();
         client.read(readBuffer);
         System.out.println("read at " + System.currentTimeMillis());
    }the isWritable if statement will always return (which is fine) and the isReadable if statement will NEVER return (which is most certainly NOT FINE!!). The readBuffer code is there just to clear out the read buffer so isReadable is only called once per data sent.
    This SEEMS to be a bug in how the selector works? I would expect to see isReadable return true whenever data is sent, but that is not the case. Now here is the real kicker ;) Go ahead and change this line:
    socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);to this:socket.register(selector, SelectionKey.OP_READ);And now it appears that isReadable is running as expected?! To let people run this code on their own, I have uploaded a copy of the entire java file here:
    http://www.electrotank.com/lab/personal/mike/NioTest.java
    Please forgive the code, it's just the smallest test harness I could make and much of it is lifted from other posts on this forum. You can test this by using Telnet and connecting to 127.0.0.1:8080. You can test the isReadable piece by just typing in the Telnet window.
    Someone else has listed something as a bug in the Bug Parade, but the test case is flawed:
    http://developer.java.sun.com/developer/bugParade/bugs/4755720.html
    If this does prove to be a bug, has someone listed this already? Is there a nice clean workaround? I'm getting really desperate here. This bug makes the NIO socket stuff pretty unusable. Thanks in advance for the help!!
    Mike Grundvig
    [email protected]
    Electrotank, Inc.

    Yeah, isReadable crashed for me too.
    My solution was to not call it. I set up two selectors for the two operations I wanted notifying (accept and read) and used them independently in different threads. The accept thread passes them over to the read thread when they're accepted.
    This way I don't need to call isReadable since it is bound to be readable otherwise it wouldn't have returned, as read is the only operation I'm being notified about.
    --sam                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Cant get server for msn to work on iphone 4

    Hi I cant get my MSN SERVER for MSN to work on my Iphone to receive and send mail I have tried the out going and incomming port codes but NO luck does anybody know how to make my MSN work on my IPhone 4 .
    thanks

    Again the operator CAN create the config file and send as an SMS . This config file contains the correct settings.
    You just open the SMS and it auto installs in the phones config bundle
    You then boot the phone down and reboot .
    It really is simple however many MVNO services can't be a**ed -that why their cheap!
    Not in dispute with you on the problem - yes it's the APN defaulting to ATT and being blocked as a non- subscriber. And compounded by the MVNO Sim card not having the correct protocols to view the APN menu item.

  • HT5622 ive verified my email information and my apple id but still cant get into my phone

    i cant get into my phone even tho i put in all the correct info

    To resolve this issue, from the Safari menu, choose Preferences > Privacy. Then, choose an option other than Always for blocking cookies.
    Note: The default option for Safari is to block cookies "From third parties and advertisers" and is recommended for most usage.
    If you want to block cookies temporarily when visiting websites, choose Safari > Private Browsing. Learn more about Private Browsing.
    I hope this will be helpful for you.

  • HT4528 I was looking at the setting and turn on the phone setting the a voice says the fuction and i cant get back to it to turn it off. i cant scroll

    I was looking at the settings and turn on the phone setting where a voice says the fuction and i cant get back to it to turn it off. i cant scroll to get back to the setting to turn it off.

    1. Triple-click the line below to select it:
    ~/.Trash
    2. Right-click or control-click the highlighted line and select
    Services ▹ Show Info
    from the contextual menu.* An Info dialog should open.
    3. The dialog should show "You can read and write" in the Sharing & Permissions section. If that's not what it shows, click the padlock icon in the lower right corner of the window and enter your password when prompted. Use the plus- and minus-sign buttons to give yourself Read & Write access and "everyone" No Access. Delete any other entries in the access list.
    4. In the General section, uncheck the box marked Locked if it's checked.
    5. From the action menu (gear icon) at the bottom of the dialog, select Apply to enclosed items and confirm.
    6. Close the Info window and test.
    *If you don't see the contextual menu item, copy the selected text to the Clipboard (command-C). Open a TextEdit window and paste into it (command-V). Select the line you just pasted and continue as above.
    Remove the Norton/Symantec product by following the instructions on either of these pages:
    Uninstalling your Norton product for Mac
    Removing Symantec programs for Macintosh
    If you have a different version of the product, the procedure may be different. Back up all data before making any changes.
    From the Safari menu bar, select
    Safari ▹ Preferences... ▹ Privacy ▹ Remove All Website Data
    and confirm. Consider installing an ad-blocker and/or a selective cookie block such as the "Ghostery" Safari extension.

  • APP-QA-16161: Cant find the Transaction Block

    When I click on Create Service Request or View Service Request form I get message
    APP-QA-16161: Cant find the Transaction Block
    The error is coming from the pre-form trigger of the CSXSRISR.fmb.
    We have copied the .fmx of this file and all associated files from other instnaces, but still the issue is present.
    Also, the issue is not present when we enable FRD trace.
    Anyone has any suggestions on the same?

    Hi,
    Please verify that you have no invalid objects in the database -- See (Note: 308927.1 - APP-QA-16161 - Can't find transaction block. Please inform system administrator).
    If the above does not help, see (Bug 7253526 - RCVTXERT: APP-QA-16161 CAN'T FIND TRANSACTION BLOCK), I believe you would need to log a SR as the solution is not mentioned.
    Regards,
    Hussein

  • I cant get any pop ups to open? i have allowed sites and still cant get anything, so turned off and still cant enlarge pictures etc thru a pop window

    i have firefox version 3.6.10, and until about a week ago, i had no problems clicking on pictures (example: on ebay) to enlarge them in a new pop window. i have tried disabling the pop up blocker completely, even though i had ebay as an "allow" site on my pop up blocker when it was enabled.
    cant get any pop up to go through. in the lower left hand corner of the window, when i click on a link that should open a pop up window, all it shows is "javascript:;" and nothing happens
    i have updated to the newest version of java and deleted older version.. still having issues

    Ouch, tough spot, but offhand I'd say some memory may have gone bad, or maybe just needs re-seating after all this time.
    Not much you can do, but try this anyway...
    PRAM reset, CMD+Option+p+r...
    http://support.apple.com/kb/ht1379
    In fact, do 3 in a row, takes a bit of time.

  • WLC 5508 Cant get access via the Mgmt Interface

    Hello everybody,
    i have a wlc 5508 (version 7.0.98.0) , if i'm pinging the service port interface or try to get access via this interface, everythings is fine, but if cant get access via the management interface. (but its pingable)
    the crazy thing is, that the LAP joined successful ti the wlc, but the Upgradetool (converting an AP to an LAP) doesnt work, because the tool cant reach the mgmt interface of the wlc.
    there are no ACLs, which are blocking the traffic between wlc and my computer
    Does anyone has an idea, what i've configured wrong???
    regrads,
    Rocco

    Interface Name                   Port Vlan Id  IP Address      Type    Ap Mgr Guest
    wlan1                                   1    16       172.16.2.10      Dynamic No     No
    management                         1    2        172.16.1.10      Static     Yes    No
    wlan2                                   1    220      172.16.3.10   Dynamic No     No
    service-port                        N/A  N/A      10.75.100.99      Static     No     No
    virtual                                N/A  N/A      1.1.1.1               Static     No     No
    and my Pc is in the 172.16.4 subnet
    i have no access to the switch port, where the controller is connected to, but i know that this port permits access to the vlans which are used

Maybe you are looking for