Are the experts wrong about non-blocking SocketChannels?

Everyone says to use the new SocketChannel and Selector for "highly scalable" server applications. So I ran a couple of tests using non-blocking (via Selector) and thread-per-connection SocketChannels.
The Selector version consumes 8x more cpu than the thread-per-connecton version!
Using JDK 1.4.1 FCS on Win2K, with 1000 socket connections each sending 1k bytes per second, the Selector version was consuming 40% cpu with 10 threads; the thread-per-connection version (using blocking SocketChannels) was only consuming about 5% cpu with 1009 threads.
So, are the experts wrong? Is there a performance problem when number of SocketChannels exceed a certain threshold?
For anyone interested, here's the source code:
Non-Blocking Server using Selector
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server4 implements Runnable
private static int port = 80;
public static void main(String args[]) throws Exception
Server4 server = new Server4();
Thread thread = new Thread(server);
thread.setDaemon(true);
thread.start();
thread.join();
public Server4() throws IOException
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress(port);
server.configureBlocking(false);
server.socket().bind(isa);
m_selector = Selector.open();
server.register(m_selector, SelectionKey.OP_ACCEPT);
Charset utf8 = Charset.forName("UTF-8");
m_decoder = utf8.newDecoder();
m_encoder = utf8.newEncoder();
public void run()
int count = 0;
try
ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
//FileOutputStream fos = new FileOutputStream("server4.dat");
//FileChannel fc = fos.getChannel();
while (m_selector.select() > 0)
Set keys = m_selector.selectedKeys();
for (Iterator itr = keys.iterator(); itr.hasNext(); )
SelectionKey key = (SelectionKey) itr.next();
itr.remove();
if (key.isAcceptable())
System.out.println("accept: " + (++count));
ServerSocketChannel server
= (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false);
channel.register(m_selector, SelectionKey.OP_READ);
else
SocketChannel channel = null;
try
if (key.isReadable())
channel = (SocketChannel) key.channel();
int bytes = channel.read(buffer);
if (bytes <= 0) // Linux does not throw IOException
channel.close(); // will also cancel key
System.out.println("connection closed " + count);
else
buffer.flip();
//fc.write(buffer);
buffer.clear();
catch (IOException ioe) // connection closed by client
System.out.println("readable: " + ioe.getMessage());
sm_logger.log(Level.INFO, ioe.getMessage(), ioe);
Throwable cause = ioe.getCause();
if (cause != null)
System.out.println("cause: "
+ cause.getClass().getName()
+ ": " + cause.getMessage());
channel.close(); // will also cancel key
--count;
catch (IOException e)
System.out.println("run: " + e.getMessage());
sm_logger.log(Level.SEVERE, e.getMessage(), e);
catch (Exception e)
System.out.println("run: " + e.getMessage());
sm_logger.log(Level.SEVERE, e.getMessage(), e);
private Selector m_selector;
private CharsetDecoder m_decoder;
private CharsetEncoder m_encoder;
private static Logger sm_logger = Logger.getLogger("Server");
Thread-Per-Connection Server
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MultiThreadServer implements Runnable
private static int port = 80;
public static void main(String[] args) throws Exception
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress(port);
server.socket().bind(isa);
int count = 0;
while (true)
SocketChannel channel = server.accept();
System.out.println("accept: " + (++count));
MultiThreadServer worker = new MultiThreadServer(channel);
Thread thread = new Thread(worker);
thread.setDaemon(true);
thread.start();
public MultiThreadServer(SocketChannel channel) throws IOException
m_channel = channel;
public void run()
ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
int bytes = 0;
try
while ((bytes = m_channel.read(buffer)) > 0)
buffer.flip();
// process buffer
buffer.clear();
System.out.println("connection closed");
m_channel.close();
catch (IOException e)
System.out.println("run: " + e.getMessage());
sm_logger.log(Level.SEVERE, e.getMessage(), e);
catch (Exception e)
System.out.println("run: " + e.getMessage());
sm_logger.log(Level.SEVERE, e.getMessage(), e);
private SocketChannel m_channel;
private static Logger sm_logger = Logger.getLogger("MultiThreadServer");
Client
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MultiClient implements Runnable
public static void main(String[] args) throws Exception
if (args.length < 1)
System.out.println("usage: java MultiClient number [host]");
System.exit(1);
int number = Integer.parseInt(args[0]);
String host = (args.length == 2) ? args[1] : "localhost" ;
Thread[] threads = new Thread [number];
InetSocketAddress address = new InetSocketAddress(host, 80);
for (int i = 0; i < number; i++)
MultiClient client = new MultiClient(address, Integer.toString(i));
threads[i] = new Thread(client);
threads.setDaemon(true);
for (int i = 0; i < number; i++)
threads[i].start();
for (int i = 0; i < number; i++)
threads[i].join();
public MultiClient(InetSocketAddress address, String id)
throws InterruptedException, IOException
m_id = id;
Charset charset = Charset.forName("UTF-8");
m_decoder = charset.newDecoder();
m_encoder = charset.newEncoder();
m_channel = SocketChannel.open();
m_channel.connect(address);
if (id.equals("0"))
Socket socket = m_channel.socket();
System.out.println("SO_SNDBUF=" + socket.getSendBufferSize()
+ ",SO_TIMEOUT=" + socket.getSoTimeout()
+ ",SO_KEEPALIVE=" + socket.getKeepAlive());
byte[] buf = new byte [1024]; // bufsize = 1K
Arrays.fill(buf, (byte) m_id.charAt(0));
m_buffer = ByteBuffer.allocateDirect(1024);
m_buffer.put(buf);
m_buffer.flip();
Thread.currentThread().sleep(50L);
public void run()
System.out.print(m_id);
try
while (true)
m_channel.write(m_buffer);
m_buffer.rewind();
Thread.currentThread().sleep(1000L);
catch (IOException ioe)
ioe.printStackTrace();
catch (InterruptedException ie)
System.err.println(ie.toString());
private String m_id;
private CharsetEncoder m_encoder;
private CharsetDecoder m_decoder;
private SocketChannel m_channel;
private ByteBuffer m_buffer;

{This is a crosspost. I posted this earlier today at http://forum.java.sun.com/thread.jsp?forum=4&thread=319822 before I stumbled on a search phrase that located this older thread.
All follow-ups should be on haam's thread instead of mine. The important point below is that NIO select() behavior (vs. threading IO)  is [b]worse under Windows but better under Solaris. This seems fundamentally broken. }
My company sells a scalable multi-user server platform built on Java 2.
It runs under Java 1.3.1 (and 1.4.0 windows) using multiple threads for communications, and 1.4.x (unix) using NIO. We were happy to see that 1.4.1 (windows) fixed the problem drastically limiting the number of selectable ports. :-)
The bad news is that whatever the VM is doing "under the sheets" to fix the problem seems to perform very poorly in terms of CPU:
I compared connecting 500 simulated users to a Solaris 8 and a Win2K box. These users were in 25 chat rooms, each sending a chat message every 30 seconds. (There was plenty of memory on each machine. There was no swapping in either case. Clock/CPU type doesn't matter as this isn't about comparing a machine to a machine, but different load characteristics -within- a machine environment.)
                Threaded IO      NIO/Select
Solaris 1.4.1     20-30%           15- 20%
Windows 1.4.1     40-50%           95-100%Numbers are % of CPU as reported by 'top' and the Win2K task manager.
Both platforms showed the expected significant improvement in memory usage when moving from standard threaded IO to NIO.
Strangely, the Windows implementation of the VM showed a significant (and unexpected) degradation of NIO performance vs. the threaded model, whereas the Solaris VM behaved as expected: NIO outperformed threaded IO.
Our best guess is that the Selector fix in 1.4.1 is implemented in some cpu-intensive way; perhaps polling. As a result, we still can't use NIO for Wintel boxes running our server. :-( To us, Selector
is still broken.
Has anyone else seen results like this? Have we missed some configuration parameter that will fix this?
I thought the big upside of using select() was supposed to be performance. :-P
F. Randall Farmer
State Software, Inc.
http://www.statesoftware.com

Similar Messages

  • Non-blocking SocketChannels

    I'm trying to learn how to use non-blocking socket channles, but I haven't found much info (nor luck) so far.
    To learn, I'm building a server and a client. The server accepts input from the clients and process it in only one thread. The clients should send Objects to the server, and the server process them and return the result also as an Object. For this, I'm trying to use ObjectOutputStream and ObjectInputStream.
    The problem I don't know how to solve is that the SocketChannel is in non-bolcking mode, so I can't use their input/output streams (I get a IllegalBlockingModeException). In the server process loop I can reconfigure the SocketChannel to blocking mode to be able to read the Object, but I can't configure it to non-blocking mode again because I get a CancelledKeyException.
    Does anyone know how to work with InputStreams and non-blocking channels? Or where to find more info about it?
    Here are the relevant part of the server code:
    Set ready = selector.selectedKeys();
    Iterator i = ready.iterator();
    while (i.hasNext()) {
       try {
          SelectionKey sk = i.next();
          i.remove();
          if (sk.isAcceptable()) {
             ServerSocketChannel ssc = (ServerSocketChannel)sk.channel();
             SocketChannel sc = ssc.accept();
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ);
          } else if (sk.isReadable()) {
             SocketChannel sc = (SocketChannel)sk.channel();
             // PROBLEM: If the channel is in non-blocking mode
             // I cannot use InputStreams
             sk.cancel();
             sc.configureBlocking(true);
             // Read the object sent by the client
             ObjectInputStream in = new ObjectInputStream(Channels.newInputStream(sc));
             Object o = in.readObject();
             // PROBLEM: Can't put the channel back to non-blocking mode
             sc.configureBlocking(false);
             sc.register(selector, SelectionKey.OP_READ); // CancelledKeyException
       } catch (...){
    }

    In my client, this is working fine:
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    for (int i = 0; i < 30000; i++) {
       oos = new ObjectOutputStream(sc.socket().getOutputStream());
       oos.writeObject(object);
       oos.flush();
       ois = new ObjectInputStream(sc.socket().getInputStream());
       Object o = ois.readObject();
    }But trying to do it like this throws a StreamCorruptedException at the server side.
    ObjectOutputStream oos = new ObjectOutputStream(sc.socket().getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(sc.socket().getInputStream());
    for (int i = 0; i < 30000; i++) {
       oos.writeObject(object);
       oos.flush();
       Object o = ois.readObject();
    }Do you know why?

  • Non-Blocking SocketChannel read give Connection timed out

    Hi,
    My program is using Non-Block NIO SocketChannel for both Server and Client sides. However, if the connection between server and client has been idle for a while, when the client try to communicate with server, it gets blocked for a while (15 minutes) and then receives the following exception:
    java.io.IOException: Connection timed out
         at sun.nio.ch.FileDispatcher.read0(Native Method)
         at sun.nio.ch.SocketDispatcher.read(Unknown Source)
         at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
         at sun.nio.ch.IOUtil.read(Unknown Source)
         at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
    How can this be since the read is in Non-Blocking mode? Also, is there anyway to determine the timeout without being blocked?

    This would mean that you are trying to read from the socket without having properly completed the connection, which timed out. I would say you are connecting in non-blocking mode but not calling finishConnect() when you get OP_CONNECT.

  • What are the steps to unload non cumulative cubes

    Dear friends,
    can any one of you let me know, What are the steps to unload non cumulative cubes.
    Thanks in Advance.
    Chandan Kumar

    Hi,
    what do you mean by unload? Do you want to delete the whole cube or just special requests.
    You should delete the requests from the top until this request where you get wrong data.
    Or press on the trash bin at the top if you want to delete the whole cube.
    Regards,
    Juergen

  • FileChannel.transferTo() using non-blocking SocketChannel

    I'm looking to use FileChannel.transfer(From/To) for performing file transfers over a network. On the uploading side I find that even though I set the SocketChannel to non-blocking mode, the loop manages to send files as large as 30MB in only a single transferTo() invocation. What I'm hoping for is to have a series of partial writes so that I might generate progress notifications, which does occur on the downloading side with transferFrom(). I don't think a file that large should be transferred in one pass so I'm thinking that this is caused by either some internal buffer allocation issue or a goof-up on my part.
    Thanks in advance for any input and here's the uploading code:
    public void upload( String fileName ) {
    FileInputStream fileStrm = null;
    FileChannel fileChan = null;
    FileLock fileLock = null;
    SocketChannel sockChan = null;
    Selector selector = null;
    try {
    // Lock the source file.
    file = new File( fileName );
    fileStrm = new FileInputStream( file );
    fileChan = fileStrm.getChannel();
    fileLock = fileChan.lock( 0L, Long.MAX_VALUE, true );
    // Open a server socket bound to an arbitrary port.
    servChan = ServerSocketChannel.open();
    servChan.socket().bind( new InetSocketAddress( 0 ) );
    // Wait for a single connection and close the server socket.
    sockChan = servChan.accept();
    servChan.close();
    sockChan.configureBlocking( false );
    selector = Selector.open();
    SelectionKey selectorKey = sockChan.register( selector, SelectionKey.OP_WRITE );
    // Loop until transfer has completed.
    int fileSize = ( int ) file.length();
    int sizeLeft = fileSize;
    while ( sizeLeft > 0 ) {
    // Wait for data to read, then transfer it.
    if ( selector.select() == 1 && selectorKey.isWritable() ) {
    sizeLeft -= ( int ) fileChan.transferTo( fileSize - sizeLeft, sizeLeft, sockChan );
    // Generate a progress notification here such as:
    // monitor.bytesTransferred( fileSize - sizeLeft );
    catch ( IOException ex ) {
    ex.printStackTrace();
    finally {
    try {
    // Cleanup.
    if ( selector != null )
    selector.close();
    if ( sockChan != null )
    sockChan.close();
    if ( fileLock != null )
    fileLock.release();
    if ( fileChan != null )
    fileChan.close();
    if ( fileStrm != null )
    fileStrm.close();
    catch ( IOException ex ) {
    ex.printStackTrace();
    -Edwin

    Actually, the sending process appears way ahead of the receiving one, where the send seems to finish in a blink while the receive takes several seconds to complete. In other words, the transferTo() completes in one loop, while the transferFrom() performs many with delays in between. I'd guess all that data is sitting in some large outbound buffer at the sender, which would explain why it seems to finish too quickly. If I split the send into smaller chunks, the two sides run quite nearly at the same pace as expected.
    The receiver already sleeps by way of a select() against a non-blocking SocketChannel, so I'll try reducing the buffer sizes as you suggest.

  • Hi I cannot make the accessibility zoom option work. What are the commands on a non Mac keyboard?

    Hi I cannot make the accessibility zoom option work. What are the commands on a non Mac keyboard?

    If you want to convert SWF to DVD in freeway, find a converter to convert SWF to normal video such as: SUPER, then burn to DVD.

  • What are the bad things about Apple Remote Desktop

    What are the bad things about Apple Remote Desktop? Need it for my assignment

    Is your assignment about managing a classroom full of Macs?
    Otherwise, Screen Sharing, or a VNC client/server, or TeameViewer.com, or LogMeIn.com might be better, and less expensive.
    ARD is intended for managing a classroom or office full of Macs. It is overkill for remotely accessing a remote Mac or two.

  • Non-blocking SocketChannel and close - huh?

    It looks like closing a socketchannel that is in non-blocking mode can result in a dead drop of the connection, with some bytes that have already been sent and accepted (as in, 'consumed' from the buffer) being completely dropped.
    In fact, I'm generally confused: Actual C non-blocking code has a similar setup for 'close' as you can see in SocketChannel's OP_CONNECT behaviour - just because you want to connect the socket doesn't mean it magically happends without blocking. Wait for a ready flag, then try again.
    It should work the same way with close (you try to close, but it may not be possible without blocking).
    Is this a huge gaping bug that no one quite figured out just yet, or did I miss something? I loathe to turn on linger, as that's just a crapshoot (you never know if it actually gets through. You could run into funny surprises once the server gets a bit busy. I'd rather not) and tends to cause massive leaks on linux, at least according to some google searches.
    There seems to be slightly better performance (in that I have always received all data sofar) if I close the socket instead of the channel (socketChannel.socket().close() instead of socketChannel.close()) - but this has been a random attempt at 'making it work', and I can't find any documentation that backs up that this will DEFINITELY not lose any information without letting me know somehow. That still sounds impossible with this approach.

    Actual C non-blocking code has a similar setup for
    'close' as you can see in SocketChannel's
    OP_CONNECT behaviour ...No it doesn't. I don't know what you mean by this.
    Closing a socket is asynchronous, but it shouldn't lose any data - if the data can be delivered it will be, followed by the FIN. You don't know when it is delivered, and you don't get to hear about any errors such as an RST coming from the other end, say if it decided to close before reading all the data, or if some intermediate router hung you up.
    I'm wondering if you are really dealing with all the short write and zero length write possibilities, i.e. whether the data isn't really still in your output buffer. Don't wish to teach you to suck eggs but there are some subtleties here.
    Setting a positive linger timeout doesn't really help because Java doesn't tell you if the timeout expired. (I only asked for this about four years ago). You get to wait while any pending data is delivered, but you still have to guess about whether it all went or the timeout expired, and the behaviour after the timeout expires is platform-dependent: some (Windows) issue an RST, others (Unix) keep trying.
    Blocking or non-blocking mode shouldn't make any difference to this (except that Linux will block on a positive linger timeout even in non-blocking mode, which is wrong), and whether you close the channel or the socket is immaterial as one calls the other anyway.
    The reason why OP_CONNECT is different in blocking/non-blocking modes is that in blocking mode it won't return until the SYN-ACK is received, while in non-blocking mode it just sends the SYN and relies on you calling connect() again (at the C level) to collect the SYN-ACK, or not - this is what finishConnect() tells you.
    tends to cause massive leaks on linux, at least
    according to some google searchesIt can't, unless you are referring to the Helix client thing, which appears to be just a badly designed C++ class library with, for some reason, its own linger implementation outside the kernel.

  • 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

  • About non-blocking Interaction mode

    I would like to know when the Forms runtime will display a dialog that allows the user to cancel the query after I have set a form in non-blocking Interaction mode.
    In a time-consuming query, the dialog must appear after
    few seconds or its depend on other condition?
    And, what is time-consuming query?
    Thank you

    it will appear in the 5 seconds with a dialog 'press Cancel button to change this database session' 5 times after you press the button.
    To mimick, you set 'query all' to 'yes', then you will see it.
    As of what is timimg-consuming, it depends on your app. performance requirment.

  • Problem about Non-blocking socket's read and write

    my aim is:when I open a socketchannel,I can use this socket which can continue send and get messages!(for example:open a socket,send a loging message,server echo,if passed,use the same socket sending other message,get echo messages....
    Here is problem sample codes:
    void ConnectServer() throws IOException
    bf = ByteBuffer.allocateDirect(1024);
    InetSocketAddress ad = new InetSocketAddress(this.servername,this.serverport);
    this.clientsocketchannel = SocketChannel.open(); //set socketchannel
    this.clientsocketchannel.configureBlocking(false);
    this.clientsocketchannel.connect(ad);
    this.slt = Selector.open();
    this.clientsocketchannel.register (this.slt,SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
    //send data
    private void SendMessage(byte[] SendMessage)throws IOException
    while (this.slt.select() > 0)//sth wrong!when I test,slt.select(500)=0
    Set readykey = slt.selectedKeys();
    Iterator readyitor = readykey.iterator();
    while (readyitor.hasNext())
    SelectionKey skey = (SelectionKey) readyitor.next();
    readyitor.remove();
    if (skey.isWritable())
    SocketChannel keychannel = (SocketChannel) skey.channel();
    keychannel.write(ByteBuffer.wrap(this.sendmessage));
    }//end while
    }//end while
    //get data
    private void GetEchoMessage()throws IOException
    while(this.slt.select(500) > 0)//sth wrong!when I test,slt.select(500)=0
    Set readykey = slt.selectedKeys();
    Iterator readyitor = readykey.iterator();
    while (readyitor.hasNext())
    SelectionKey skey = (SelectionKey) readyitor.next();
    readyitor.remove();
    if (skey.isWritable())
    SocketChannel keychannel = (SocketChannel) skey.channel();
    keychannel.read(bf);
    public static void main(String[] arg)
    connectserver(..);
    SendMessage(...);
    GetEchoMessage();
    SendMessage(...);
    GetEchoMessage();

    private void ConnectServer() throws IOException
    � bf = ByteBuffer.allocateDirect(1024);
    �� InetSocketAddress ad = new InetSocketAddress(this.servername,this.serverport);
    �� this.clientsocketchannel = SocketChannel.open(); //set
    socketchannel
    �� this.clientsocketchannel.configureBlocking(false);
    �� this.clientsocketchannel.connect(ad);
    �� this.slt = Selector.open(); � this.clientsocketchannel.registerthis.slt,SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);
    <b>
    //send data</b>
    private void SendMessage(byte[] SendMessage)throws IOException
    � while (this.slt.select() > 0)//<font color="#FF0000"><i>wrong,when test,this.slt.select(500)=0,why??</i></font>
    �{
    ��� Set readykey = slt.selectedKeys();
    ��� Iterator readyitor = readykey.iterator();
    ��� while (readyitor.hasNext())
    ��� {
    ������ SelectionKey skey = (SelectionKey) readyitor.next();
    ������ readyitor.remove();
    ������ if (skey.isWritable())
    ������ {
    �������� SocketChannel keychannel = (SocketChannel) skey.channel();
    �������� keychannel.write(ByteBuffer.wrap(this.sendmessage));
    ������ }
    ��� }//end while
    � }//end while�
    <b>
    //get data</b>
    private void GetEchoMessage()throws IOException
    � while(this.slt.select(500) > 0)<font color="#FF0000"><i>//wrong,when
    test,this.slt.select(500)=0</i></font>
    � {
    ��� Set readykey = slt.selectedKeys();
    ��� Iterator readyitor = readykey.iterator();
    ��� while (readyitor.hasNext())
    ��� {
    ����� SelectionKey skey = (SelectionKey) readyitor.next();
    ����� readyitor.remove();
    ����� if (skey.isWritable())
    ����� {
    ������� SocketChannel keychannel = (SocketChannel) skey.channel();
    ������� keychannel.read(bf);
    ����� }
    ��� }
    � }
    public static void main(String[] arg)
    � ......
    � connectserver(..);
    � SendMessage(...);
    � GetEchoMessage();
    � .......
    � SendMessage(...);
    � GetEchoMessage();
    � .......

  • Where are the experts? 'Calendar Button'

    Dear all,
    I have a form A, which contain 2 push buttons PB_A & PB_B to invoke the calendar.
    and i have two text items which will get the value of the calendar and i put
    'date_lov.get_date(sysdate,'BLK01.START_DATE',100,100,'Select Date','Ok','Cancel',TRUE,FALSE,TRUE);' in the trigger key-listval
    but when i click on the button 'Enter-Query' and i want to invoke the calendar by any push button PB_A or PB_B it gives me "FRM-41009: Function key not allowed. Press %s for list of valid keys"
    Thanks in advance
    ShoOoSh

    Not sure of the date calendar function you are calling, but you can't navigate out of a block that is in enter query mode. I suspect the call to date_lov.get_date actually wants to move your focus to some other block.
    this function may not be callable from enter query mode.
    --pat                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Placed Excel file - why are the dates wrong?

    I have just relinked a number of Excel spreadsheets in a Mac InDesignCC document and all the dates are now 4 years and a day later than they should be.
    I've searched the forums and it appears that this is related to the Excel 1900/1904 date system but I can't find any solutions.
    The Excel files are from Windows Excel 2010 and look fine in Excel 2011 for Mac and in Apple Numbers.
    So any ideas how can I get InDesign to also show the dates correctly?
    Thanks,
    Graham
    PS asking my client to update all his files to an Apple Mac date system isn't an option!
    PPS I've tried changing the preference in Excel 2011 to "Use 1904 Date System" but that just adds 4 yrs to the dates in the Excel spreadsheets!!

    I have just relinked a number of Excel spreadsheets in a Mac InDesignCC document and all the dates are now 4 years and a day later than they should be.
    I've searched the forums and it appears that this is related to the Excel 1900/1904 date system but I can't find any solutions.
    The Excel files are from Windows Excel 2010 and look fine in Excel 2011 for Mac and in Apple Numbers.
    So any ideas how can I get InDesign to also show the dates correctly?
    Thanks,
    Graham
    PS asking my client to update all his files to an Apple Mac date system isn't an option!
    PPS I've tried changing the preference in Excel 2011 to "Use 1904 Date System" but that just adds 4 yrs to the dates in the Excel spreadsheets!!

  • Question to the experts? about saving and retrieving numbers

    Question
    is there a java method to store a number in the memory and recall it
    like M+ and M- in the Microsoft Calculator?
    when the M+ button is clicked it store the numbers
    When M- button is clicked it recalls the number
    lets say ive used
    i.e using the String s method which is straight forward
    actionPerformed Event e blaah blah blah
    //add your handling code here
       String s;
            intA;
            double PhoneNumber;
            s=txtA.getText();
           A=Integer.parseInt(s);
           PhoneNumber= (double)Math.round(A);
           s=String.valueOf(PhoneNumber);
          txtRexhaul.setText(s);now when the M+ button is clicked it stores both the values in "txtA" and "PhoneNumber"
    and when the M- button is clicked it recalls the stored numbers and sets it back
    using the .setText("") method in "txtA" and "PhoneNumber"
    is this possible ?
    Solutions are appreciated thanks again
    Edited by: AK-Emm on Sep 27, 2008 2:30 PM

    oh ok
    lets use stack then ilike node
    if it will work just like storing numbers on a calculator M+ and M- functions this is a stack method
    class Node {
       String item;
       Node next;
    Node first  = new Node();
    Node second = new Node();
    first.item  = "1222441"; // Clients phone number lets say mine Rexhaul Cartier
    second.item = "33322211"; // Clients phone number lets say yours
    Node old first=first;
    first=first.next; //when the M- button is clickedi get stuck after this i need to simplify this thats where your expertise comes in,
    example of a calculator lets say a standard has a Store Button M+ and a recall Button M-
    with the String S method as mentioned earlier
    when the M+ button is clicked it stores both Textfield "A" and TextField "RexhaulCartier"
    when the M- button is clicked it recalls the stored number just like setText(); to the selected textFields
    let me simplify this i.e ?---> A // what goes into A
    A=1// you type the value
    1(store)---> A // stores 1 in variable A when M+ button is clicked
    RCL A// recall what was stored in variable A by clicking M- button
    A= 1
    you get the picture?
    i.e if you use Microsoft OS i.e Vista Xp 2000 etc run the calculator in accessories youll see what i mean
    when you want to store the answer you press the M+ button when you want to recall it you press M- it displays the stored answer thanks for your time to help me out i really appreciate your help p....
    Edited by: AK-Emm on Sep 27, 2008 3:29 PM

  • OCCI and non-blocking

    I'd like to use the OCCI interface in a non-blocking mode. Does anyone have any experience with this? Looks like I need to use a combo of OCI and OCCI calls to set the OCI_HTYPE_SERVER handle with the OCI_ATTR_NONBLOCKING MODE. However, my stmt->executeQuery() method seems to be throwing an exceptions, which I would have though would have been the OCI_STILL_EXECUTING error, but it's not. The exeception is an "ORA-32103 error from OCI call". If I continue to do another stmt->executeQuery(), I eventually get an access exception.
    Anyone have any code snippets using OCCI in non-blocking mode?

    I use threads. ACE/TAO to be precise.
    I have singleton class that manages the Oracle environment and connection as well as being a statement
    factory.
    Just have a thread perform your stmt->executeXXX() method and you will not need to worry about non-blocking.
    That's how I do it and it works well.

Maybe you are looking for