Blocking socket is not blocking.

Hello
I'm using the java.net.Socket class in JDK1.4 and hope that the read() on InputStream will block until there is data.
However, the call to read() is not blocking but return me the end-of-stream symbol (-1). Because I want it to block (no timeout set) to save CPU time, how I do. Following, please find a code-example:
public class Server implements Runnable {
private java.net.Socket clientSock;
public Server(java.net.Socket Sock) {
clientSock = Sock;
new Thread(this).start();
public void run() {
try { while (true) { clientSock.getInputStream.read(); }
} catch (Exception Ex) { /* Never occur */ }
public static final void main(String args[]) {
try {
java.net.ServerSocket servSock = new java.net.ServerSocket(54321);
while (true) { new Server(servSock.accept()); }
} catch (Exception Ex) { /* Never occur */ }
This example takes 100% CPU load on my machine as soon as there is one connection. Why? Broken JDK?

Try putting a sleep call in your loop...otherwise this single thread will take up all you CPU and will not yeild to the other threads. Set you SLEEP_TIME based on how long you want the thread to sleep before polling for data on the socket...
try {
while (true) {
clientSock.getInputStream.read();
Thread.sleep(SLEEP_TIME);
} catch (Exception Ex) { /* Never occur */ }
Hello
I'm using the java.net.Socket class in JDK1.4 and hope
that the read() on InputStream will block until there
is data.
However, the call to read() is not blocking but return
me the end-of-stream symbol (-1). Because I want it to
block (no timeout set) to save CPU time, how I do.
Following, please find a code-example:
public class Server implements Runnable {
private java.net.Socket clientSock;
public Server(java.net.Socket Sock) {
clientSock = Sock;
new Thread(this).start();
public void run() {
try { while (true) {
) { clientSock.getInputStream.read(); }
} catch (Exception Ex) { /* Never occur */ }
public static final void main(String args[]) {
try {
java.net.ServerSocket servSock = new
= new java.net.ServerSocket(54321);
while (true) { new Server(servSock.accept()); }
} catch (Exception Ex) { /* Never occur */ }
This example takes 100% CPU load on my machine as soon
as there is one connection. Why? Broken JDK?

Similar Messages

  • Ad Block Plus is not blocking ads

    I downloaded ad block plus 3 years ago and it worked perfectly. Suddenly, it stopped blocking ads. I have tried to use the troubleshooting advice, and have followed the parts I understand. But it still does not work, although it seems to have been downloaded because I see the option of removing it when I go to Tools and Options.
    Help!

    http://adblockplus.org/forum/

  • Block Caller feature not blocking calls on iOS7.0.2

    I am still receiving calls from contacts I have blocked. I have an iPhone 4S using iOS 7.0.2. Does anyone know how to prevent this?
    Thanks Very Much! CindiS

    Nothing.
    If you block a number from the iPhone you do not hear any ring. If the blocked caller leaves a voicemail it will be in your voicemail folder under blocked callers. You will not get any notification sound for these voice mails.
    The text messages you will never see. The sender will never know they were blocked.
    Good Luck

  • Broken Pipe with Non-blocking Socket

    Hello,
    I write a Unix Agent who connect on a Windows Server with socket...
    Working well on Linux but on Solaris my problem is:
    -When my agent is running before server at connection all seems OK: Connect, Select and Getsockopt but when I try to send data I have always EPIPE Signal but I can receive datas from server !
    - When my agent is strarting after the server all it's Ok
    I don't unserstand this appears on Solaris SPARC 8 and Solaris 9 Intel ...
    Please Help is there something special with non-blocking sockets on Solaris ?
    Thanks

    Can't help you much but what I would recommend is that you
    insure that your pipes are opened for both read/write, even
    though you are only going to read or write from it. This insures
    that the pipe does not close down when you hit EOF.

  • Non blocking socket

    I have an application that can act as a client or as a server. It connects as a client by default. If there is no existing server, an error is raised and the app reconnects as a server.If there is a server, the application will successfully connect as client.
    Ideally, what should happen is that a server will advertise its socket and should proceed with the main program. However, it should always be ready with an incoming connection. When there is no remote computer connected, the application can only access its local files, however it should be able to access the files in the remote computer when a connection exists. But when there is no remote computer, it should not block the program from proceeding normally (only that some functionalities are lost)
    Currently, the system is ok when when client and server applications are running. But the problem is that the server application blocks until a client connects to it.
    Any suggestions?

    This is the whole point of the NIO that has been introduced in 1.4. See this link: http://developer.java.sun.com/developer/technicalArticles/releases/nio/

  • Can somebody explain: blocking socket?

    When a serversocket call accept(), what's it really doing? Does it listen the port for ever until get a request?
    If so, what's the meaning of non-blocking socket? Doesn't it listen the port but wait for a message?
    Anyone, help me.

    when you call accept the thread which calls this is blocked until either
    1) a connection is made
    2) or the socket timeout. The socket timeout is set with the setSoTimeout method
    if there has been no connection made in the timeout time (in milliseconds)
    then an InterruptedIOException is thrown by the accept method and the thread is unblocked, if a connection has been made then this returns a socket.
    Non-blocking socket
    When this is called then the method returns straight away, either with a connection or not, it is up to the user to implement a loop to keep checking for a connection.

  • Non blocking socket method?

    Is there a method like:
    Socket s = serversocket.accept();that does not block a program?
    Or a method for checking if there are any connections waiting to be accepted like:
    if(serversocket.connectionsWaiting()) {
    socket = serversocket.accept();
    }Thanks, Rufus

    If you check out my Taming the NIO Circus thread there is an Echo server that does this.

  • Writing Java Non-Blocking Socket Server for  Winsock Client

    Hi.
    Im a newbie to Sockets. I need to write a Non-Blocking Socket server (using java.nio) that accepts connection and reads the data sent by WinSock clients, and write them to another winsock client. Its quite intriguing. How do I do that? Is it possible?
    Thanks in advance
    Arun

    Well, in traditional 4.2 BSD sockets, you'd fill up a set of filedescriptors of connections (an array of bits usually), and push that in the read parameter of a call to 'select'. Select then blocks until at least one of the file descriptors become available for reading, or writing if you also made an fd_set full of file descriptors (but you can usually write freely to a socket, so there is not much use for that). Then you start finding out which of these file descriptors have actually become available for reading, and you pass those to a bunch of worker-threads. The advantage is that your set of worker-threads can be quite small, while your number of connections can still be quite large (unless, of course, everyone of your clients start talking all at once, but that is no different from the one-socket-one-thread-model that java.net.* forces upon you).
    In java, the 'select' call is replaced by a call to java.nio.channels.Selector.select(); and then the fishing out of the selected stuff comes from java.nio.channels.Selector.selectedKeys().
    To add a thingy to a selector, use (for example) java.nio.channel.ServerSocketChannel.register(Selector, ops, att);
    whereby the ops parameter is the kind of action you'd like to select this channel for; SelectionKey.OP_READ etc..
    The workerthread bit is also easy to write, but I leave that to you as an exercise.

  • Detecting When a Non-Blocking Socket Is Closed by the Remote Host

    Hi,
    Using NIO non blocked sockets how do I detect when a Non-Blocking Socket Is Closed by the Remote Host?
    What I have read is:
    The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.
    I have written a server test program using NIO and an applet connecting to the server program via sockets.
    When I after a successful connection shuts down the browser following happens: The code below comes in an endless loop though mySelector.select returns 0 every time. (The selector is registered for OP_READ). size = 1.
    while (true) {
    int n = mySelector.select();
    int size = mySelector.keys().size();
    if (n == 0) continue;
    Is this an expected result?
    How do I get to know what client has lost connection?
    My environment:
    W2000
    java 1.4.1 build 1.4.1_01-b01
    Browser used: IE 5.0
    Many thanks for your help on this matter!
    Regards Magnus Wistr�m

    What you're doing looks OK to me.
    I wonder whether your thread is being interrupted by Thread.intterupt() somewhere. Try putting a Thread.interrupted() before the select call.
    Sylvia.

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • UTL_TCP (blocking or non-blocking sockets mode)

    Hi for All,
    Please, someone knows if the UTL_TCP using blocking or non-blocking sockets mode? I did a search but can not find this information.
    Regards,

    Blocking only occurs when you attempt to read from the socket and there's no data to read. (in which case, the time out setting applies if specified)
    This is however not that robust in my experience. UTL_TCP provides a peek method (returns byte size of socket buffer) that tells you whether or not there is data for that socket. This enables you to verify that you read on that socket will not be a blocking call.
    I prefer using this method, as dealing with a timeout approach results in run-time behaviour issues (either a call waiting too long, or a call timing out too quickly).

  • Non blocking sockets in jdk 1.3.1

    Hello guys
    i am working on client server programs which has socket connections. i am using serversocket and socket objects. At some point i may have multiple clients connected to the server and if one socket gets blocked i am unable to send data to other clients( sockets) also.
    If i know correctly Sockets are of blocking type by default.
    How can i solve this problem in jdk1.3.1?
    IS java.nio.* ther only solution? if yes should i change to 1.4.
    Waiting for u guys reply
    Thanks

    HI you can use a setSoTimeout(timeout) method to set a timeout for read() method in input stream , so since you set a timeout, read() method will block for that amount of time and after it will throw SocketTimeoutExceptions... http://java.sun.com/j2se/1.3/docs/api/java/net/Socket.html#setSoTimeout(int)
    Socket s = new Socket(.....);
    int timeout = 10; //(milliseconds)
    s.setSoTimeout(timeout);
    try {
    int byte = s.getInputStream().read(); // will block for 10 miliseconds or return a byte from stream
    if (byte == -1) ; // stream closed
    } catch(java.net.SocketTimeoutException e) {
    // there is no data to read
    }other way is to use available() method from inputStream and then
    Socket s = new Socket(.....);
    InputStream input  = s.getInputStream();
    int available = input.available(); // it return 0 if there is no data to read or number of bytes available to read
    byte[] buf = new byte[maxBufSize];
    try {
    if (available != 0) {
    s.getInputStream().read(buf,0,available);
    String message = new String(buf,0,available);// if available ==0 then you will get empty string
    } catch(java.io.IOException e) {
    }but you would not be able to find out that client closed connection (because you will never get (-1) from read()), if he closed you always get 0 bytes available, so it is up to you
    Good luck

  • NIO blocking socket returns too soon

    Hi,
    I'm having a strange behaviour: a read() call on a blocking socket (I've double checked) returns before it's full. It's not a timeout issue since the SO_TIMEOUT option is set to 0 (infinity).
    Any hint?
    JL

    That's how it's supposed to work.
    From the javadoc for ReadableByteChannel.read():
    A read operation might not fill the buffer, and in fact it might not read any bytes at all. Whether or not it does so depends upon the nature and state of the channel. A socket channel in non-blocking mode, for example, cannot read any more bytes than are immediately available from the socket's input buffer; similarly, a file channel cannot read any more bytes than remain in the file. It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read.

  • Select() does not block

    I cannot provide simple code for this yet. Nondeterministically,
    my calls to Selector.select() do not block. That is, they return
    immediately, and they return 0. There are no calls to
    Selector.wakeup() in the program, and I check that
    isInterrupted() == false from the thread that invokes select().
    The Javadoc states that these are the only two circumstances in
    which a return of 0 from select() should be possible.
    When this starts happening, it happens consistently ad infinitum,
    but it doesn't start happening in every execution.
    This happens with JDK 1.4.1-RC but NOT in JDK 1.4.0. I cannot
    easily roll back to JDK 1.4.0 because the OP_WRITE select()
    behavior has changed, and what I distribute must work with later
    versions of the JDK.
    I realize that, without a simple test case, it will be hard for anyone
    in this forum to diagnose this. I am hoping that, nevertheless,
    someone has some good speculation.
    I must say, I wish I had coded this in C++. This NIO seems to be
    rather shoddy so far.
    Thanks in advance,
    Juan Leon

    What platform are you using? I took a look and quickly found myself looking at a native method call in a platform-specific class. (sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(), specifically.) The provider (SelectorProvider.provider().getClass().getName()) might be helpful in diagnosing this. On my system (JDK 1.4.1_01, Win XP) it is: sun.nio.ch.WindowsSelectorProvider.
    With a little help from Jad and some hand editing of the formal arguments to poll0(), I get:
    private int poll() throws IOException {
        return poll0(pollWrapper.pollArrayAddress,
            Math.min(totalChannels, 1024), readFds, writeFds, exceptFds, timeout);
    private native int poll0(long address, int channels,
        int[] readFds, int[] writeFds, int[] exceptFds, long timeout);selectNow() pretty much just calls doSelect(0L) in a synchronized block, so I think hoping it will reset things is futile.
    WindowsSelectImpl.doSelect(long) looks like this:
        protected int doSelect(long l) throws IOException {
            if (channelArray == null)
                throw new ClosedSelectorException();
            timeout = l;
            processDeregisterQueue();
            if (interruptTriggered) {
                resetWakeupSocket();
                return 0;
            adjustThreadsCount();
            finishLock.reset();
            startLock.startThreads();
            try {
                begin();
                try {
                    subSelector.poll();
                } catch (IOException ioexception) {
                    finishLock.setException(ioexception);
                if (threads.size() > 0)
                    finishLock.waitForHelperThreads();
            } finally {
                end();
            resetWakeupSocket();
            finishLock.checkForException();
            processDeregisterQueue();
            return updateSelectedKeys();
        }As you can see, when all is said and done it calls the native method mentioned above to do all the work, which most likely calls your system's poll() (or possibly select()?), which may be where your problem actually lies. Another poster suggested it may choke on certain channels (closed w/ half-open socket) -- is it possible for you to remove them from the set before calling select? (I know you shouldn't have to, but....)
    By the way, updateSelectedKeys() iterates over the helper threads calling the subclass's processSelectedKeys() method, which in turn calls processFdSet() three times: once each for the readFds, writeFds, and exceptFds. This is what actually computes the return value, and the problem could be here, but isn't likely to be, since you say it isn't even blocking.
    Anyway, I've gone on long enough, and I'm sure you can use Jad (or some other decompiler) as well as I can. I'm certainly no nio expert (in fact, I haven't used Selector), and this is only what I found after a quick glance into the code.
    Whoa! While proofreading this, that "if (interruptTriggered)" block suddenly jumped out at me. If interruptTriggered is getting stuck on that could cause your problem. It's private volatile boolean and is false initially, then set in wakeup() and reset in resetWakeupSocket().
    Jad (v1.5.8e2) coughed while decompiling resetWakeupSocket(), but I think it's:
        private void resetWakeupSocket() {
            synchronized (interruptLock) {
                if (!interruptTriggered)
                    return;
            resetWakeupSocket0(wakeupSourceFd);
            interruptTriggered = false;
        }resetWakeupSocket0() is another native method. You'll get some insight into your problem from studying WindowsSelectorImpl (or whatever the implementation is on your platform), but you're going to find that you need to look at the several native methods being called to really determine what's going on.
    Good luck,
    David R. Conrad

  • Adobe Creative Cloud (Desktop) does not work properly. The application is blocked : it could not be launch neither stopped. I'm on MAC Yosemite OS, does anyone know how to remove it properly or to force its stop. It does not appear in the launched applica

    Adobe Creative Cloud (Desktop) does not work properly. The application is blocked : it could not be launch neither stopped. I'm on MAC Yosemite OS, does anyone know how to remove it properly or to force its stop. It does not appear in the launched applications.

    I received no error message. The application was just trying to find applications unsuccessfully.
    I am using MAC OS 10.10.1
    I tried to uninstall the application  but it seems that a kind of deamon is still installed thus providing me to reinstall properly. Do you know where are the elements to remove in order to get my machine just like before ?
    Otherwise I would have to reinstall everything and this would be a pain.
    Thanks for your help.

Maybe you are looking for

  • When i try to open emails in yahooo the emails won;t open?

    when i click on the emails to open the they don;t open.

  • Tcode to view the list of orders with reason for rejection

    Hi friends, Can any one tell the T.code or report to view the  list of sales orders or Scheduling agreements with Reason for Rejection updated. Kindly help. Regards, K.Vivek

  • Unable to join network

    Hi everyone Please help me I can`t connect to wi-fi at all I haven`t used it for about 2 months now i found out it won`t connect to ANY network I`ve tryed it all, restore as new, reset ect And i`m very busy that i can`t make it to Apple store Please

  • Printing 2-D barcodes

    hi folks,           i have two doubts reagsrding barcodes. 1. what is the difference between single dimension barcode and two dimesional barcode. 2. can we print 2-D barcodes on SAP Scripts/smartforms on a data matrix printer. printer deatils are as

  • Basic questation about how works DPM

    HI all, sorry how DPM detect which files is changed I must copy to replika ? Or how is created replika . DPM also reguester create full backup and then use incremental backup copy-and-write method ?  thanx Falcon