Block again after InputStream.read() return -1

Hello,
I've got the following problem: I call read() on my InputStream object until the function return -1. The read() call is done in a loop. After that i start processing the received data. The socket is not closed and i want to start a blocking read() call again. But this doesn't work. Instead the read() return -1 again and again..... This make sense to me because there are actually no data, but i expected that read() is blocking again.
Does anyone know this problem?
By the way: Can i change my screen name. I typed in some stupid stuff as I think i could change is later.
Thanks
Christian

read() returning -1 means that the other end has closed the connection. All you can do is close yours. There will never be any more data so there is nothing for it to block for.

Similar Messages

  • Why can't InputStream.read() be interrupted?

    I have a native application that launches a java application. To allow for the communication between the two applications, the native app launches the java app with stdin and stdout redirected to a file handles. The Java application creates a thread to read from System.in. Everything works great -- UNTIL . . .
    . . . the native app closes the communcation handles and exits, leaving the java application blocking on the InputStream.read().
    My question is why doesn't the blocking InputStream.read() get interrupted when the communcation handle in the native app closes? This appears to be a BUG in Java. I would expect to get an exception or error on the read when the handle on the other sides exits.
    My ideas to work around this would include changing the IPC communcation to a network protocol like sockets, or MMF. However, redirecting stdin and stdout seemed to be the simpliest IPC. Any other ideas or suggestions?
    Cheers,
    Kyley

    Thanks for all your replies. Hearing others express the same idea that it should work the way that I had thought made me revisit how the native application was launching the application and how the handles were redirected.
    After getting things working on UNIX (Sun Solaris), I looked again at the code (which I didn't write) that launched the java application on Windows. After rewriting the code, the original code wasn't duplicating stdin & stdout and closing one of the original handles. Once that was done properly, AMAZINGLY everything worked as I had intended it to work.
    Thanks again for the time to reply.
    Kyley

  • SerialPort: inputStream.read blocks, never return -1

    I use javax.comm package to transfer files between two virtual com ports (looped)
    Send a file from com3, and receive file from com4, but at reciever side, inputStream.read(buffer) never return eveb though I close the outputstream at the sender.
    Here is code:
    is: serialPort.getInputStream();
    os: serialPort.getOutputStream();
    //sender:
    //fis: FileInputStream
    try {
         int i =0;
         while ((counter=fis.read(buffer)) > 0 ){
              fileSize += counter;
              debugInfo(i + ": "+counter + "bytes read");
              os.write(buffer,0,counter);
              i++;
         debugInfo(fileSize + " bytes read totally");
         os.flush();
         fis.close();
         //close os when no file need transfering
         os.close();
    } catch(IOException e) {
         e.printStackTrace();
    }file receiver
    fos: FileOutStream
    try {
         int i =0;
         while ((counter=is.read(buffer)) >0){ //blocks and never return
              counter=is.read(buffer);
               fileSize += counter;
               debugInfo(i + ": "+ counter + " bytes read");
               fos.write(buffer,0, counter);
               i++;
    debugInfo(fileSize + " bytes write totally");
    fos.flush();
    fos.close();
    debugInfo("fos closed");
    is.close();
    } catch(IOException error) {
         error.printStackTrace();
    }Anything I have done wrong? or anything better solution? Thanks

    oops, sorry for copied wrong codes. Thanks for your remind. The second read was used with while (is.availble()), when I post, I forgot to remove it. You are right, if I have read twice, I will not even get the right file, since I only write every second buffer in.
    Here I update the receiver, I can get the whole file correctly, but can't get EOF.
    //file receiver
    //fos: FileOutStream
    try {
         while ((counter=is.read(buffer)) >0){ //blocks and never return
              fileSize += counter;
               fos.write(buffer,0, counter);
    fos.flush();
    fos.close();
    is.close();
    } catch(IOException error) {
         error.printStackTrace();
    }

  • Bug with InputStream.read after BufferedReader.readLine in a Thread ?

    I just found something strange when reading bytes on a socket after reading lines.
    I'll show you an example :
    In this example, when a connexion is established, I launch a thread where a single line of String then 3 bytes are read from the socket. I use BufferedReader.readLine for the String line then just InputStream.read to read the 3 bytes.
    The results are quite random. Sometimes it works, sometimes not (most times it doesn't)... it seems to always work under linux (but haven't tested it as many times than on windows). Most of the time the program is stuck on the "socket.getInputStream().read(bytes);" line with 0 bytes available. I tried to do the same thing outside of a thread, I thought it worked better beaucause I was able to run it without any problem but it doesn't work anymore when I test it again.
    I can't say if I'm doing something wrong or if it's a java bug (I've got JDK 1.6.0_03-b05).
    Can you please have a look a this little example and maybe test it and let me know if it works or not. I tried to code my own readLine function and it seems to work with it but I'd like to know if it's a bug or what. Thank you.
    Server side :
    import java.io.*;
    import java.net.*;
    public class testServer extends Thread {
         private Socket socket;
         public testServer(Socket testSocket)
              socket = testSocket;
         public void readData() throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String str;
              str = br.readLine();
              System.out.println(str);
              System.out.println("Bytes available : " + socket.getInputStream().available());
                    //Try to read the bytes
                    byte[] bytes = new byte[3];
                    //STOPS THERE UNDER WINDOWS, BUT WORKS WITH LINUX
              socket.getInputStream().read(bytes);
                    //Simple "ack" to say to the client that he can close the connexion
              socket.getOutputStream().write(0);
              socket.getOutputStream().flush();
                    //Print the bytes values
              for(byte value : bytes)
                   System.out.println(value);
         public void run()
              try {
                   readData();
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   ServerSocket welcomeSocket = new ServerSocket(3333);
                   while(true)
                        new testServer(welcomeSocket.accept()).start();
              } catch (Exception e) {
                   e.printStackTrace();
    }client side :
    import java.io.*;
    import java.net.*;
    public class testClient {
         public static void main(String[] args) {
              try {
                            //Some test values
                   byte[] testValues = new byte[]{1,2,3};
                   Socket socket = new Socket(InetAddress.getLocalHost(), 3333);
                            //Send the line through the socket
                   BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   bw.write("HELLO WORLD\r\n");
                   bw.flush();
                            //then the bytes
                   socket.getOutputStream().write(testValues);
                   socket.getOutputStream().flush();
                            //Just waits for the server's ack to close the connexion
                   socket.getInputStream().read();
                   socket.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    It's your bug.
    When you create a BufferedReader and ask it to read a line, the first thing it does is to read a whole buffer full of data (hence the name of the class) from its underlying input stream. That's probably about 4000 characters or something like that. It stores that internally and then starts doling it out in response to calls to readLine() and so on.
    Then when you go back to reading from the underlying input stream, those 4000 or so characters are already gone from it. You have no access to the data the BufferedReader is hanging on to this way. All you can do is to start reading at the point after that whole buffer, which is not what you want.

  • HT201363 Dear Reader  I have forgotten the answers to my security-questions. So it says that i will get an e-mail to reset my questions, but i have not gotten an e-mail? So i tried it again (after a month) and it still doesen't work. I really need to know

    Dear Reader
    I have forgotten the answers to my security-questions. So it says that i will get an e-mail to reset my questions, but i have not gotten an e-mail?
    So i tried it again (after a month) and it still doesen't work. I really need to know what's wrong :/
    Thank You for helping me

    Alternatives for Help Resetting Security Questions and Rescue Mail
         1. Apple ID- All about Apple ID security questions.
         2. Rescue email address and how to reset Apple ID security questions
         3. Apple ID- Contacting Apple for help with Apple ID account security.
         4. Fill out and submit this form. Select the topic, Account Security.
         5.  Call Apple Customer Service: Contacting Apple for support in your
              country and ask to speak to Account Security.
    How to Manage your Apple ID: Manage My Apple ID

  • HT2500 Sometimes after I read an email and leave it in my Inbox, I then can't open it again. I can reply to it, but I can't open it again. This is happening more and more often.

    Sometimes after I read an email and leave it in my Inbox, I then can't open it again. I can reply to it, but I can't open it again. This is happening more and more often.

    I see you are on 10.6.8.   There have been a few Mail problems of late, particularly I notice, since the last security update.
    Suggest you run the Snow Leopard combo update Mac OS X 10.6.8 Update Combo v1.1  (again) even if you have previously done it.  Won't do any harm.
    Then check software update and try again with mail.   You should be on mail 4.6. (1085)

  • Logged Out session can be accessed again After logout (DAD authentication)

    Hello,
    Please find the details of my problem below:
    SCENERIO:
    Current Authentication: No Authentication (USING DAD)
    Authorization: MYAUTH
    Frequency: Once Per Session
    declare
    lv_retval boolean;
    lv_srec pkg_myutil.r_sessionrectype;
    begin
    begin
    -- This is NOT Apex Session. I am checking the entry in a table to make sure user is logged in
    -- and the link is not opened directly. In short making sure user opened the Apex link from the
    -- Oracle Forms application.
    lv_srec :=pkg_myutil.get_session_info(:P1_SID);
    if lv_srec.valid_session then
    lv_retval := TRUE;
    else
    lv_retval := FALSE;
    end if;
    exception
    when others then
    lv_retval := FALSE;
    end;
    return lv_retval;
    end;
    The Application Security property Authorization is set to : MYAUTH
    Logout Navigation Bar Entries-URL TARGET: http://myapp.mycompany.com/pls/apex/apex_custom_auth.logout?p_this_app=105&p_next_url=http://mycompany.com
    ( I cannot put this in the Authentication Logout URL as using -DATABASE- as sentry function (DAD authentication) gives me error: No functional attributes may be set when page sentry function is '-DATABASE-'.))
    so i directly modified the navigation bar entry
    Now I open the apex link from my forms application, and it Works fine. For example
    http://myapp.mycompany.com/pls/QRYONLYDAD/f?p=105:1:2524984933940261::NO::P1_SID:0137099300:
    The authorization function takes the P1_SID value and checks in database,finds the entry so returns TRUE to display the page 1 which i call Menu page.
    If I click logout, it works and takes me to the Mycompany home page.
    My question:
    If save that link and try to access it again AFTER LOGOUT, it still displays the page. Although the session is logged out, how come it still allows to access the page? The authorization function also doesn't fire which would have prevented it atleast. How APEX knows it still a valid session even after logout happens?
    I can see that Since there is DAD authentication, the login happens automatically........ but I cannot change that method. What other option do i have?
    Please help.
    Jay

    1.) Code for the function:
    Basically we are using a private DBMS_PIPE to pass a randomly generated string and read that pipe from Apex using get_session_info. Nothing to do with Apex Session. We just want to make sure the user opened the Apex link from the application.
    function get_session_info (p_session_id varchar2) return pkg_myutil.r_sessionrectype is
    rv_sessionrec eft.pkg_myutil.r_sessionrectype;
    lv_status NUMBER;
    lv_app_id varchar2(20);
    lv_EMPID VARCHAR2(20);
    lv_timeout BINARY_INTEGER := 0; --A timeout of 0 allows you to read without blocking. otherwise the pipe will keep waiting and our purpose won't be solved
    lv_rmstatus number;
    begin
    begin
    -- Valid Session theme: If the pipe doesnot exist means the url is not requested from inside the Forms application.
    lv_status := DBMS_PIPE.RECEIVE_MESSAGE(p_session_id,lv_timeout);
    IF lv_status <> 0 THEN
    raise_application_error(-20003,'Error while receiving.Status = ' || lv_status);
    END IF;
    DBMS_PIPE.UNPACK_MESSAGE(lv_app_id);
    DBMS_PIPE.UNPACK_MESSAGE(lv_EMPID);
    if lv_EMPID is null then
    raise_application_error(-20004,'User EMPID is null in the session info.');
    end if;
    -- construct return record
    rv_sessionrec.session_id:=p_session_id;
    rv_sessionrec.valid_session :=TRUE;
    -- remove pipe
    lv_rmstatus:=DBMS_PIPE.REMOVE_PIPE(p_session_id);
    if lv_rmstatus <> 0 then
    null; -- think what to do
    end if;
    exception
    when others then
    rv_sessionrec.session_id:=p_session_id;
    rv_sessionrec.valid_session :=FALSE;
    end;
    return rv_sessionrec;
    end get_session_info;
    2.) I guess you are right. But doesn't Apex use the Userid and password hardcoded in the DAD? because it displays the username in DAD on the page footer. But It will authenticate everytime. So I want to put another layer so that my pipe verification code executes everytime which can decide whether to show the page or redirect to a error page.
    If i put in a On-Load Before Header Process on Page 1 with the pl/sql code, is there a way there to redirect to different page? I couldn't think of a way to do it. Then i can remove the code from authorization scheme and add to the On-Load process?
    Does this help any?
    Thanks for your prompt response.
    Thanks,
    Jay

  • JDBC Blocks again when try to get new connections.

    Hi,
    again, my tomcat freezes today, and i must stop/start tomcat to get new connections:
    i checked MaxDB server and a Running thread causes Timer to block.
    the output of command show t_cnt of the running maxdb thread is:
    --------------------  T270  USER              ( pid =      0 ) ---------------
    remote_node   : 192.168.99.1                          remote_pid    : 0
    dispatcher_cnt: 618065                                command_cnt   : 99418
    exclusive_cnt : 1035660104                            self_susp_cnt : 4
    Resume count 0  total 155        History [ T2 T2 T2 ]
    dev_read_io   : 177                                   dev_read_pg   : 177
    state_vwait   : 0          state_vsleep  : 45         state_vsusp   : 144
    rcv_rpl_count : 99418      rcv_rpl_long  : 0          avg_rcv_rpl_t : 0.0000
    dev_que_len_0 : 177        dev_que_len_1 : 0          dev_que_len>1 : 0
    prio_total    : 2                                     prio_from_oth : 2
    some of the java blocked thread example is:
    "http-80-173" daemon prio=10 tid=0x0000000043edd000 nid=0x7ce8 waiting for monitor entry [0x000000005564c000..0x000000005564da90]
       java.lang.Thread.State: BLOCKED (on object monitor)
            at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:917)
            - waiting to lock <0x00002aaab91895b0> (a org.apache.tomcat.dbcp.pool.impl.GenericObjectPool)
            at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:96)
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
            at org.exolab.castor.jdo.engine.DatabaseRegistry.createConnection(DatabaseRegistry.java:399)
            at org.exolab.castor.jdo.engine.TransactionContextImpl.getConnection(TransactionContextImpl.java:203)
            at org.exolab.castor.persist.TransactionContext.query(TransactionContext.java:644)
            - locked <0x00002aab12f5a5d8> (a org.exolab.castor.jdo.engine.TransactionContextImpl)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:458)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:414)
            at com.supridatta.bean.DataPersist.consulta(DataPersist.java:536)
            at com.supridatta.servlet.SupridattaServlet.doConsultarControl(SupridattaServlet.java:730)
            at com.supridatta.servlet.SupridattaServlet$9.resolve(SupridattaServlet.java:294)
            at com.supridatta.servlet.SupridattaServlet.processaOperacao(SupridattaServlet.java:144)
            at com.supridatta.servlet.SupridattaServlet.doAppletControl(SupridattaServlet.java:114)
            at com.supridatta.servlet.SupridattaServlet.service(SupridattaServlet.java:1747)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:183)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:568)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    like this exists about 189 java blocked threads all waiting for this one:
    "Timer-4" daemon prio=10 tid=0x0000000043ae7000 nid=0x51b3 runnable [0x0000000042128000..0x0000000042128b10]
       java.lang.Thread.State: RUNNABLE
            at java.net.SocketInputStream.socketRead0(Native Method)
            at java.net.SocketInputStream.read(SocketInputStream.java:129)
            at com.sap.dbtech.rte.comm.BasicSocketComm.receiveData(BasicSocketComm.java:577)
            at com.sap.dbtech.rte.comm.BasicSocketComm.receive(BasicSocketComm.java:666)
            at com.sap.dbtech.rte.comm.JdbcCommunication.execute(JdbcCommunication.java:41)
            at com.sap.dbtech.jdbc.ConnectionSapDB.execute(ConnectionSapDB.java:536)
            - locked <0x00002aaabce3bc80> (a com.sap.dbtech.jdbc.ConnectionSapDB)
            at com.sap.dbtech.jdbc.ConnectionSapDB.execute(ConnectionSapDB.java:461)
            at com.sap.dbtech.jdbc.ConnectionSapDB.isClosed(ConnectionSapDB.java:746)
            at com.sap.dbtech.jdbc.trace.Connection.isClosed(Connection.java:400)
            at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.isClosed(DelegatingConnection.java:346)
            at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:324)
            at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.validateObject(PoolableConnectionFactory.java:312)
            at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.evict(GenericObjectPool.java:1217)
            - locked <0x00002aaab91895b0> (a org.apache.tomcat.dbcp.pool.impl.GenericObjectPool)
            at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool$Evictor.run(GenericObjectPool.java:1341)
            at java.util.TimerThread.mainLoop(Timer.java:512)
            at java.util.TimerThread.run(Timer.java:462)
       Locked ownable synchronizers:
            - None
    then seeing all this appears that com.sap.dbtech.jdbc.ConnectionSapDB.isClosed(ConnectionSapDB.java:746) do something that blocks all connections, but i cant understand if T270 is related to this Timer-4 java thread.
    any idea?

    Hi Lars,
    I updated all things, Java, Linux, MaxDB, i discovered that the problem isnt with network, but with some kind of deadlock at database side, for example:
    1) user 1 insert something on table A
    2) user 2 starts a long running transaction with poor SQL statement that locks the table A.
    3) user 3 opens a connection to run an SQL statement that queries table A.
    4) all java threads that need a new JDBC connection get blocked because step 3 never returns a new connection, and DBCP synchronization never goes out.
    here is the thread of step 2:
    java.lang.Thread.State: RUNNABLE
            at java.net.SocketInputStream.socketRead0(Native Method)
            at java.net.SocketInputStream.read(SocketInputStream.java:129)
            at com.sap.dbtech.rte.comm.BasicSocketComm.receiveData(BasicSocketComm.java:577)
            at com.sap.dbtech.rte.comm.BasicSocketComm.receive(BasicSocketComm.java:666)
            at com.sap.dbtech.rte.comm.JdbcCommunication.execute(JdbcCommunication.java:41)
            at com.sap.dbtech.jdbc.ConnectionSapDB.execute(ConnectionSapDB.java:536)
            - locked <0x00002aab1ed9d560> (a com.sap.dbtech.jdbc.ConnectionSapDB)
            at com.sap.dbtech.jdbc.ConnectionSapDB.execute(ConnectionSapDB.java:461)
            at com.sap.dbtech.jdbc.ConnectionSapDB.doConnect(ConnectionSapDB.java:398)
            at com.sap.dbtech.jdbc.ConnectionSapDB.<init>(ConnectionSapDB.java:109)
            at com.sap.dbtech.jdbc.DriverSapDB.connect(DriverSapDB.java:222)
            - locked <0x00002aaabc74ade0> (a com.sap.dbtech.jdbc.DriverSapDB)
            at org.apache.tomcat.dbcp.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
            at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
            - locked <0x00002aaabc896988> (a org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory)
            at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:974)
            at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:96)
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
            at org.exolab.castor.jdo.engine.DatabaseRegistry.createConnection(DatabaseRegistry.java:399)
            at org.exolab.castor.jdo.engine.TransactionContextImpl.getConnection(TransactionContextImpl.java:203)
            at org.exolab.castor.persist.TransactionContext.query(TransactionContext.java:644)
            - locked <0x00002aab1e8d9348> (a org.exolab.castor.jdo.engine.TransactionContextImpl)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:458)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:414)
            at com.supridatta.bean.DataPersist.consulta(DataPersist.java:536)
    and here is the thread at step 3:
    java.lang.Thread.State: BLOCKED (on object monitor)
            at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
            - waiting to lock <0x00002aaabc896988> (a org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory)
            at org.apache.tomcat.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:974)
            at org.apache.tomcat.dbcp.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:96)
            at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
            at org.exolab.castor.jdo.engine.DatabaseRegistry.createConnection(DatabaseRegistry.java:399)
            at org.exolab.castor.jdo.engine.TransactionContextImpl.getConnection(TransactionContextImpl.java:203)
            at org.exolab.castor.persist.TransactionContext.query(TransactionContext.java:644)
            - locked <0x00002aab1e898f98> (a org.exolab.castor.jdo.engine.TransactionContextImpl)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:458)
            at org.exolab.castor.jdo.engine.OQLQueryImpl.execute(OQLQueryImpl.java:414)
            at com.supridatta.bean.DataPersist.consulta(DataPersist.java:536)
    I inspected the database side, still really running, database results comes, but without releasing the connection, and if i wait the time or no user need a new connection, i never get thread blockeds, appears that MaxDB locks all connections if the newly created connection executes some SQL after acquiring that connection.
    I see some blocks too at java finalizer, where one thread running is stucked getting a connection.
    all this is just guess, maybe I'm wrong, but for now i will end this thread as we need see how this system will perform with all updates made.
    best regards.
    Clóvis

  • Bug in the ServerSocket InputStream.read()

    I believe there is a bug in the ServerSocket InputStream.read() method.
    This is demonstrated under Windows XP, running 1.4.0_01-b03
    I am looking for confirmation and an examination of my assumptions for this.
    There is nothing that suggests the InputStream.read() method should block on a EOL, yet it does.
    This is demonstrated with the following code.
    To reproduce uncomment one of the 'Case' sections in the MyServer code. Compile both classes. Run the MyServer then MyClient code.
    The expected result for ALL cases should be
    ***socket start
    text1
    text2
    But for the first case the last line is not printed. Note that for case 3 it does work, and the only exception is that available() is called.
    The InputStream of the server resolves to java.net.SocketInputStream. The read() method calls the read(byte, int, int) method (which how I guessed that calling available would produce different results.)
    //-----------------Client
        import java.io.*;
        import java.net.*;
        public class MyClient
            private MyClient() {}
            static public void main(String argv[])
                try
                    Socket s = new Socket("127.0.0.1", 50080);
                    OutputStream os = s.getOutputStream();
                    String text = "text1\r\ntext2";
                    os.write(text.getBytes());
                    os.flush();  // We know it was sent.
                    // Important!  The socket remains open!
                    while(true)
                        Thread.currentThread().sleep(60 * 1000);
                catch(Throwable e)
                    e.printStackTrace();
    //----------- Server
        import java.net.*;
        public class MyServer implements Runnable
            Socket s;
            public MyServer(Socket s)
                this.s = s;
            static public void main(String argv[])
                try
                    ServerSocket ss=new ServerSocket(50080);
                    while(true)
                        Socket s=ss.accept();
                        Thread t = new Thread(new MyServer(s));
                        t.start();
                catch(Throwable e)
                    e.printStackTrace();
            public void run()
                try
                    System.out.println("***socket start");
                    java.io.InputStream ins=s.getInputStream();
                    // Case 1: Does NOT work
                    int j;
                    while((j=ins.read())!=-1)
                        System.out.write(j);
                    // Case 3: Does work
                    while (true)
                        int len = ins.available();
                        if ((len < 0) || s.isClosed()) break;
                        byte b[] = new byte[len];
                        ins.read(b);
                        for (int i=0; i < len; i++)
                            System.out.print((char)b);
    // Case 3: Does work
    while (true)
    int len = ins.available();
    if ((len < 0) || s.isClosed()) break;
    for (int i=0; i < len; i++)
    int b = ins.read();
    System.out.print((char)b);
    System.out.println("***socket end");
    catch(Throwable e)
    e.printStackTrace();

    System.out is line buffered. (I can only hope that I might have noticed this myself if I had been smart enough to use the same output method.)
    Ok so it isn't a socket problem. But I still don't see anything that documents the behavior.
    System.out is documented as a java.io.PrintStream. And that is actually the class that implements it.
    Nothing in the documentation for PrintStream, the methods, the FilterOutputStream or even OutputStream would suggest the different behavior.
    C works the same way; this never prints "world" on most systems:C works that way because of the way file descriptors work and the way that the buffers for those are handled. And how it works is undefined, a C implementation is allowed to handle it anyway it wants.
    But this Java and not C. That means at a minimum that the behavior must be the same on all OSs. But given that the behavior is not documented then it could be that it is left to the implementation of the C library that the java io library is built upon. And that is not a good thing (in terms of normal java.)
    The following demonstrates the behavior using the two output methods...
          String text = "text1\r\ntext2";
          byte[] b = text.getBytes();
          System.out.println("--- print using print() sleep for 10 secs after");
          for (int i=0; i < b.length; i++)
             System.out.print((char)b);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- print using write() sleep for 10 secs after");
    for (int i=0; i < b.length; i++)
    System.out.write((int)b[i]);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- done");

  • Data block information after deletion of data

    Hi , If I have deleted a row in a particular table then which meta data table in oracle will record that the no of bytes got deducted.
    I have checked in this table for perticular table before deletion and after deletion but there is no difference in number...DBA_SEGMENTS
    Edited by: 883279 on Jan 28, 2013 4:56 AM

    883279 wrote:
    Hi , If I have deleted a row in a particular table then which meta data table in oracle will record that the no of bytes got deducted.
    I have checked in this table for perticular table before deletion and after deletion but there is no difference in number...DBA_SEGMENTS
    Edited by: 883279 on Jan 28, 2013 4:56 AM When you delete a row in a table, oracle marks the block as free block and it does not actually frees the block. The subsequent insert statement uses this information and overwrites the block with new data.
    cehck this out, I have a table
    SQL> create table t
      2  as
      3  select *
      4    from all_objects;
    Table created.Now i run this
    SQL> set autotrace on
    SQL>
    SQL> select count(*) from t;
      COUNT(*)
        213321
    Statistics
             28  recursive calls
              0  db block gets
           2960  consistent gets
           2879  physical reads
              0  redo size
            517  bytes sent via SQL*Net to client
            488  bytes received via SQL*Net from client
              4  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processed
    SQL> select count(*) from t;
      COUNT(*)
        213321
    Statistics
              0  recursive calls
              0  db block gets
           2884  consistent gets
              0  physical reads
              0  redo size
            517  bytes sent via SQL*Net to client
            488  bytes received via SQL*Net from client
              4  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processedCheck the consistent gets in the second qyery its 2884.
    Now i delete all the rows from table
    SQL> delete from t;
    213321 rows deleted.Now i again run the query
    SQL> select count(*) from t;
      COUNT(*)
             0
    Statistics
              0  recursive calls
              0  db block gets
           2884  consistent gets
            306  physical reads
              0  redo size
            514  bytes sent via SQL*Net to client
            488  bytes received via SQL*Net from client
              4  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processedYou can see the consistent gets is same 2884, so oracle goes through all the data blocks even after
    we delete them.
    Now i truncate the table
    SQL> truncate table t;
    Table truncated.
    SQL> select count(*) from t;
      COUNT(*)
             0
    Statistics
              1  recursive calls
              1  db block gets
              6  consistent gets
              0  physical reads
             52  redo size
            514  bytes sent via SQL*Net to client
            488  bytes received via SQL*Net from client
              4  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processedNow the HWM is reset and the blocks are released.

  • Socket channel read return

    client server java nonblocking SocketChannel
    at the server do writes using this:
    socketChannel.write(byteBuffer);
    At the client end do a read
    socketChannel.read(inBuffer);
    When does the client read method return ?. Assume inBuffer is empty and is bigger than byteBuffer. Does it wait until it gets all of a single write or if there is an internet delay does it return with only part of the write bytes?
    Can read return with only some of the bytes sent in a single write ?
    The point am getting at is can inBuffer after a read have 2 partial write packets, or several write packets with perhaps partial packets at the start and end ?
    thanks
    p butler

    With TCP/IP read() can return any number of bytes from 1 to the size of the buffer (also 0 bytes if you have a non-blocking socket). The sending operating system, the receiving operating system, and all routers/firewalls/etc in between can break up and/or combine writes any way they want to. TCP is a stream protocol, not a packet protocol; "packet" or write() boundaries are not preserved.
    There are a couple of common ways to send "packets":
    A line based protocol. Each "packet" is a single line of text. If the actual payload data can contain \r or \n characters, those need to be escaped with a suitable escape character. Other packet terminators can be used also. e.g. "\n.\n" (= a period on a line of its own.)
    Length+data. Before sending a "packet", send an e.g. 4-byte value that tells how long the packet is. In the receiver, read until you have that many bytes. Note that even the 4-byte length header can be split up so that you may need to do four read() calls to get them all! DataInputStream has a readFully() method, or you can write your own static utility; see reply 5 here: http://forum.java.sun.com/thread.jspa?threadID=677542

  • Published site has "Â"s after each hard return.

    I finally got my site to publish (not on imac), but after each hard return, and in some unexplained places, there are "Â"s and, periodically, another funky rounded "E" symbol. I tried to change the font to see if that helped, but it didn't make a difference. Any ideas?

    That "test" is just to determine what causes the problem and in this case it looks like the server setting. It's not so much that it's "wrong" but, being a school, maybe it's just set up in the "old" way. Again according to the page:
    "iWeb pages are in UTF-8 encoding so that they can accomodate all languages, not just English and those of W. Europe"
    So, now that we know that the server is forcing everyone to view using Latin encoding instead of Unicode, you can either have them change it (and, again there may be a good chance they won't understand the request, but give it a try) OR change it yourself IF you have an .htaccess (or .charset) file.
    At the bottom of the page, it mentions that if these aren't available to you, then you can open your .html pages with TextEdit (set to Latin) and manually remove those characters OR open your pages one at a time with Text Edit set to UTF-8 encoding, then do Save As and choose the Western Latin ISO.
    If you can get your OIT guys to set this up FOR you, it will make a lot less work for you. If you can't, then it's not the end of the world, you'll just have to re-save all your docs (before uploading) so that their server won't display the problem characters.

  • HT4864 I am getting a triangle with an exclamation point next to my inbox...it says: There may be a problem with the mail server or network. Verify the settings for account "MobileMe" or try again.  The server returned the error: Mail was unable to log in

    I can send but cannot recieve email
    This is the messege I am gewtting:
    There may be a problem with the mail server or network. Verify the settings for account “MobileMe” or try again.
    The server returned the error: Mail was unable to log in to the IMAP server “p02-imap.mail.me.com” using “Password” authentication. Verify that your account settings are correct.
    The server returned the error: Service temporarily unavailable

    Also if I go to system preferences accounts and re-enter the password it fixes the glitch sometimes.

  • HT4314 Hello, I have an Iphone 3GS and can't connect to Game Center.  It recognizes my apple ID account, states it was never used with Game Center. Then asks for country, birthdate, then returns to ask country again, then birthdate, and returns to the loo

    Hello, I have an Iphone 3GS and can't connect to Game Center.  It recognizes my apple ID account, states it was never used with Game Center. Then asks for country, birthdate, then returns to ask country again, then birthdate, and returns to the loop. Never ends the loop unless I cancel the setup process.  I have restored the iphone to the factory settings and restored the backup, but did not work. Any suggestions on what can be the problem? thank you.

    I just read another post that says you can go into a game that allows for multiple players and utalizes game center and enter your account information that way.  I haven't tried it yet, but it seems to work for others that had this issue.

  • I am using iPhone 4 from the last one year and went dead and got it replaced by paying Rs.12500/- to Nyasa Sion Koliwada Mumbai Service Provider but now again after 38days the problem has started, what do i do? Is this is the quality & service we boost?

    I am using iPhone 4 from the last one year and went dead and got it replaced by paying Rs.12500/- to Nyasa Sion Koliwada Mumbai Service Provider but now again after 38days the problem has started, what do i do? Is this is the quality & service we boost? On visiting the store we get only one reply you may write to Apple directely. we have the similar kind of problem with iPad which is being used by my wife Mr.Neelam Vij and paid Rs.16000/- to get it replaced within a year & 6months use. so in totality we have paid Rs.28500/- + Rs. 3000/- diagnostic charges.
    1. iPhone 4 , 32 GB Black with Sr. No. 88******A4T
    2. iPad 2, 16GB White with Sr. No.DL*******KPH
    Moreover, we have no information to contact whom. even the replace set has a warranty of only three month which further confirm that Apple itself is not confident wheather product will last after replacement for more then three month. Such kind of happening do not encourage anyone to recomend this product to anyone. Would appriciate a faster response to our problem if someone from Apple is going to read this email.
    Thanks & Regards
    A K Vij
    <Personal Information Edited by Host>

    http://support.apple.com/kb/he57?viewlocale=de_de
    India
    (91) 1800 4250 744
    www.apple.com/in/support/
    hope it helps

Maybe you are looking for

  • IPhone 5 Activation Error

    Hi My wife's iphone 5 shows an activation error that this device is not registered as a part of the iPhone developer program please register at developer program portal. Interesingly she is not developer but my son got a password from a friend (who i

  • How to get the ADF Mobile Client extension

    Hi all, Please post some link in which I can download the ADF Mobile Client extension for Jdeveloper 11.1.1.4.0 directly to my local disk. I have tried going through Help --> Check for updates in Jdeveloper but my proxy does not allow it. so the only

  • How i can connect ipad with ipad mini via bluetooth

    how i can connect ipad with ipad mini via bluetooth?

  • BUG on CS3 (intel) importing DWG/DXF - resolved

    Hi, here is a new bug on AI CS3 working on an Intel Mac. Importing a big Autocad DXF/DWG always said "not enough memory"... I've 4GB Ram, even if you update DWG/DWG.aip But the same file is opened on a G5 with less Ram. Restarting AI CS3 in Rosetta m

  • How to load IDVD (only) from ILife'11

      I am waiting on delivery of ILife '11 package. How do I install (only) IDVD from this package? I have IOS Mountain Lion and it came with IMovie,Iphoto and Gagageband.  I believe they are included in ILife'11 along with some other apps.  My need is