Can SocketChannel.write return -1 ?

Hi,
In the SSLEngine documentation sample code it mentions handling a -1 returned by Channel.write() if the channel is closed.
This is the only place I've ever seen it mentioned, there's nothing in the javadoc, and I've never come across it in practice.
Can anybody confirm that this is just a mistake - or is it something my code needs to handle ?
regards
Tony Seebregts

I've just submitted this as a bug. It occurs twice in the sample: once in the I/O section and once in the shutdown section. The tests for num == -1 and the associated empty code block and comment should be deleted. The code seems to have been copied & pasted from the read() block, where a -1 return is indeed valid.
Also in the shutdown section it incorrectly has
while (myNetData().hasRemaining())which should be
while (myNetData.hasRemaining())Also surely myNetData needs to be flipped before the write and compacted afterwards, which means that the test should really be not hasRemaining() but position() > 0. hasRemaining() would only work if the buffer was already flipped.

Similar Messages

  • SocketChannel.write() throws IOException instead of returning 0

    I would like your opinion.
    When a send buffer is full in the OS, should a channel's write()
    return 0, or throw an exception? If an exception, should it be the
    same exception (IOException) thrown when truly exceptional events
    happen (e.g, a connection drop)?
    On Win32, SocketChannel.write() internally calls WSASend(). When
    WSASend() returns WSAEWOULDBLOCK, write() throws IOException. I
    think it should return zero instead, or at least throw an exception
    that can be distinguished easily (by other than parsing the
    IOException.getMessage())
    Should I submit a bug?
    Thanks,
    Juan

    The java doc for write() says it should return zero. If you have a simple test case that demonstrates the behavior you describe and it is not already in the bug database, then yes. You should file the bug report.

  • Mavericks 10.9.3.  Can I write a Rule in the Mail app and tell the rule to return an email to the sender?  I have already trsuggestions?

    Mavericks 10.9.3.   MacBook. Can I write a Rule in the Mail app to return an email to Sender?  I have tried many, many times but no luck so far.  Is it even possible, or am I wasting my time?

    There is no specific option to do that, although you can redirect a message if it meets certain criteria. I believe if you wanted to bounce it back to the sender, then you would need an AppleScript to run. If you do some Google or MacUpdate searching you may find an existing script for this purpose.

  • SocketChannel.write() blocking application

    Greets,
    I'm developping a huge application and got a latency/block problem using the write(ByteBuffer) method on a Socket from a socketchannel connection.
    Running java 1.5 (diablo) on Freebsd 6 servers, 4Gb ram (2.2 allocated to jvm), with dual xeon dual-core (total 4 cores)
    Here is the application schema :
    - A thread accepting connexion on the socketchannel
    - A thread selecting keys with data to process, enqueuing it after some basic checks on a command FIFO
    - A thread getting commands from the FIFO and processing 'em, generating answers on 4 answer FIFOs
    - 4 threads (1 per FIFO) to get answers and send 'em back to the socket.
    The application usually runs with 4500-5000 simultaneous clients.
    My problem is that the only write() method sometimes takes over 20ms to write a message, with a length smaller than 50 bytes.
    As I got about 25000 answers to process each second, when some of 'em decide to be slow, the 4 threads runs slowly, and all the connected clients are suffering of that latency, for the few minutes needed to empty the FIFOs.
    Every client socket get about 5 answers per second.
    On about 1 hour running, there are about 3 'peaks' of slowness, that I cannot explain yet. That's why I'm in need of advices !
    I monitored the application when such case happens. TOP indicates 40% cpu idle, JVM memory got >500Mb free, network runs @ about 1.2Mbps, where maximal transfer rate is >20Mbps. netstat -m told me no erros, and a large amount of free buffers available.
    As the only slow process is the write() method that usually runs faster than 1ms each call, but in those case I got delays over 20ms.
    freebsd tcp default sendbuffer size is 64k, receive buffer is 32k
    Commands average received size is below 1k, Answers average sending size below 8k.
    This application is running live, and as I cannot emulate 5000+ connections with a similar beahviour to test withour being sure that won't crash all.
    What points could be responsible of such slow write() calls ? Seems it's not CPU, not RAM, not network itself...
    I suppose it's the network buffers that are causing problems. But I don't really know if I have to fit 'em to a lower size, fitting my requirements, or to a larger size, to be sure there won't be full buffers blocking all ?
    I need advices. Thanks for your ideas !
    Bill

    Hmm. So you're happy to lose data?
    A few comments:
    (a) SocketChannels are thread-safe. I don't think you need the synchronization at all, unless maybe multiple writing threads are possible. I would eliminate that possibility and the sync myself.
    (b) If you're getting write delays of 30ms occasionally, the sync must also take 30ms at the same points if it is doing anything at all, i.e. if the possibility of multiple writing threads does exist. So maybe it doesn't?
    (c) I would have a good look at this:
    http://forum.java.sun.com/thread.jspa?threadID=459338
    and specifically the part on how to manage a channel that presents write blocks, using OP_WRITE when it happens and turning it off when it doesn't.
    (d) You seem to be using one output buffer for all channels. You might be better off using a small one per channel. Then that way you don't clear, you just do put/flip/write/compact, and if the write returned 0 just post OP_WRITE for next time around the select loop. Then you won't lose any data at all, except to a client who really isn't reading: you can detect that situation by keeping track of the last successful write time to a channel, and when there is pending data and the last write is too long ago have a think about what the block means in terms of the application. Maybe you should just disconnect the client?
    (e) It would be interesting to know how many times the write loop looped when you get these large delays, and also what the data size was, and also to know that for the other cases to see if there is a difference.
    (f) Generally from a fairness point of view I prefer not to have write loops, just one attempt and if it returns even a short read I post OP_WRITE as above. Otherwise you're spending too long servicing one channel.
    You can contact me offline via http://www.telekinesis.com.au if you like.

  • SocketChannel.write()

    I've written a non-blocking server and am trying to test it with a client that uses the traditional (blocking) I/O. The problem I'm running into is when the server tries to write data to the client, it seems to take an inordinate amount of time.
    Often times the SocketChannel.write() method will return zero and write nothing to the socket when it has a perfectly good ByteBuffer available to be written. The Javadoc for the SocketChannel.write() states this is normal:
    Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.
    So I put the following statement in the code:
    while ((retVal = socketChannel.write(outputBuffer)) == 0);However, this is proving to be quite slow, sometimes taking over half a second to complete a write of around 1000 bytes.
    While this solution delivers all of the data, it is slow. Has anybody run into this, and if so, found a better solution?
    Thanks,
    Ken

    I feel compelled to reply to myself to keep this alive, so to add:
    It seems like the delays being experience here would not happen with blocking sockets and that this is a function of NIO. What I don't understand is why socket channel takes so long to know when it can write again. Waiting over half a second for one write of a 1000 byte message is not acceptable.
    Is it because I am not using a Selector? Would that tell me the channel is ready any faster? I wouldn't see why. Or is it because the client application is reading the data too slowly?
    Any help would be appreciated.
    Ken

  • Does SocketChannel.write() block

    I have a server communicating with it's clients using NIO and therefore SocketChannel's. When data are send to clients, the method SocketChannel.write(ByteBuffer) are used. The question is then, does the execution time depend of SocketChannel.write() depend on the speed of the client to receive data? Does the the method block in any way, or does it just send what is possible and then returns?

    If you have the channel in blocking mode, it also depends on how fast the client is reading. If the client isn't reading at all, ultimately its receive buffer will fill up, then the sender's sending buffer will fill, and then the write will block waiting for space in the send buffer; once the client starts reading again, space will become available and the write can complete. That's not to say that every write waits for the completion of every prior read, it's a matter of buffering and windowing, and the effect is rather decoupled because of the presence of two intermediate buffers. However it certainly can occur.

  • Can you write an excel file on client machine instead of on the server

    I am trying to user cfSpreadSheet functon. The first question I have is, can you write the file on a client machine? I tried but they all end up on the server drive. Scecond question, is there a way to do row and column range formating in CF9.0? SpreadsheetFormatCellRange function is only available for ColdFusion server version 9.01.
    Thanks.

    To expand on Dan's answer: CF doesn't have any interaction with the client browser at all: client->server comms are handled by the client and the web server; the web server simply asks CF to provide the response data if the file requested is a CF file.  But even then all CF does is process the requested file and return data to the web server.
    Also, one of the restrictions of the HTTP protocol is that that there is *no* *way* that the server can write to the client machine.  All it can do is send data to the client agent (eg: a web browser) in response to the client agent requesting it.  Can you imagine the sort of security problems one would open one's self up to if a remote web server could write to your PC????
    Adam

  • How can I write a program that compiles without warnings?

    I tried the following with the 1.5 beta-compiler (build 28; I think):
    class Y {
         public static final class Pair<X,Y> {
           private X fst;
           private Y snd;
           public Pair(X fst, Y snd) {this.fst=fst; this.snd=snd;}
           public X getFirst() { return fst; }
           public Y getSecond() { return snd; }
           public String toString() { return "("+fst+","+snd+")"; }
      public static void main(String... args) {
         Pair[] pairArr = new Pair[10];              // supposed to be an array of Pair<Integer,Integer>
         for (int i=0; i<pairArr.length; i++)
             pairArr[i] = new Pair<Integer,Integer>(i,i);
         for (int i=0; i<pairArr.length; i++) {
             Pair<Integer,Integer> p = pairArr; // unchecked warning
         System.out.println(p);
         Integer first = p.getFirst();
         Integer second = p.getSecond();
    // ... more stuff ...
    It turns out that I get an unchecked warning when I extract an element from the array of pairs. Okay, that's fine. How can I avoid the warning? I had expected that an explicit cast would help.
      Pair<Integer,Integer> p = (Pair<Integer,Integer> )pairArr;
    With a cast I'm telling the compiler: "I _know_ what I'm doing; please trust me." But the compiler still issues a warning.
    How can I write a warning-free program in this case? The only thing I can think of, is not using the parameterized type Pair in its parameterized form. But it's not the idea of Java Generics that I refrain from using parameterized types. What am I missing?

    It turns out that I get an unchecked warning when I
    extract an element from the array of pairs. Okay,
    that's fine. How can I avoid the warning? I had
    expected that an explicit cast would help.
    Pair<Integer,Integer> p = (Pair<Integer,Integer>
    )pairArr;
    With a cast I'm telling the compiler: "I _know_ what
    I'm doing; please trust me."  But the compiler still
    issues a warning.  Yes, but at least you were able to change the warning from "unchecked assignment" to "unchecked cast" which is a little shorter ;-)
    Seriously , since arrays of generic types are disallowed, there is probably no way to get rid of these warnings - which makes a strong point for eliminating "unchecked" warnings altogether (see the other thread "selectively suppressing compiler warnings")
    Cheerio,
    Gernot

  • I am connecting an external USB HDD and I can see it on my Apple Macbook Air. BUT this drive is READ only. How can I write to it?

    I am connecting an external USB HDD and I can see it on my Apple Macbook Air. BUT this drive is READ only. How can I write to it?

    Drive Partition and Format
    1.Open Disk Utility in your Utilities folder.
    2. After DU loads select your hard drive (this is the entry with the mfgr.'s ID and size) from the left side list. Click on the Partition tab in the DU main window.
    3. Under the Volume Scheme heading set the number of partitions from the drop down menu to one. Click on the Options button, set the partition scheme to GUID then click on the OK button. Set the format type to Mac OS Extended (Journaled.) Click on the Partition button and wait until the process has completed.
    4. Select the volume you just created (this is the sub-entry under the drive entry) from the left side list. Click on the Erase tab in the DU main window.
    5. Set the format type to Mac OS Extended (Journaled.) Click on the Security button, check the button for Zero Data and click on OK to return to the Erase window.
    6. Click on the Erase button. The format process can take up to several hours depending upon the drive size.
    Steps 4-6 are optional but should be used on a drive that has never been formatted before, if the format type is not Mac OS Extended, if the partition scheme has been changed, or if a different operating system (not OS X) has been installed on the drive.

  • Can we write function in select statement?

    i have function and it has Out parameter,so in this case can i write select statement for my function to retrieve the value?

    Or, you could use pipelined function - i guess.
    Like ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>create or replace type a_obj as object
      2    (
      3       e_nm  varchar2(30),
      4       e_sal number(7,2)
      5    )
      6  /
    Type created.
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>create or replace type a_rec as table of a_obj;
      2  /
    Type created.
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>create or replace function multi_return(e_cd in number)
      2  return a_rec
      3  pipelined
      4  is
      5    cursor c1
      6    is
      7      select a_obj(ename, sal) as a_det_rec
      8      from emp
      9      where empno = e_cd;
    10     
    11      r1 c1%rowtype;
    12  begin
    13    for r1 in c1
    14    loop
    15      pipe row(r1.a_det_rec);
    16    end loop;
    17  
    18    return ;
    19  end;
    20  /
    Function created.
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>
    satyaki>select * from table(cast(multi_return(&e_no) as a_rec));
    Enter value for e_no: 7369
    old   1: select * from table(cast(multi_return(&e_no) as a_rec))
    new   1: select * from table(cast(multi_return(7369) as a_rec))
    no rows selected
    Elapsed: 00:00:00.02
    satyaki>
    satyaki>
    satyaki>select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO JOB1      DOB
          7521 WARD       SALESMAN        7698 22-FEB-81     226.88        500         30 SALESMAN
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1815       1400         30 SALESMAN
          7788 SCOTT      ANALYST         7566 19-APR-87     598.95                    20 ANALYST
          7839 KING       PRESIDENT            17-NOV-81       7260                    10 PRESIDENT
          7844 TURNER     SALESMAN        7698 08-SEP-81       2178          0         30 SALESMAN
          7876 ADAMS      CLERK           7788 23-MAY-87     159.72                    20 CLERK
          7900 JAMES      CLERK           7698 03-DEC-81     1379.4                    30 CLERK
          7902 FORD       ANALYST         7566 03-DEC-81    5270.76                    20 ANALYST
          7934 MILLER     CLERK           7782 23-JAN-82     1887.6                    10 CLERK
          7566 Smith      Manager         7839 23-JAN-82       1848          0         10 Manager   23-JAN-89
          7698 Glen       Manager         7839 23-JAN-82       1848          0         10 Manager   23-JAN-89
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO JOB1      DOB
          7599 BILLY      ANALYST         7566 10-JUN-09       4500                    30
    12 rows selected.
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>select * from table(cast(multi_return(&e_no) as a_rec));
    Enter value for e_no: 7698
    old   1: select * from table(cast(multi_return(&e_no) as a_rec))
    new   1: select * from table(cast(multi_return(7698) as a_rec))
    E_NM                                E_SAL
    Glen                                 1848
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>/
    Enter value for e_no: 7599
    old   1: select * from table(cast(multi_return(&e_no) as a_rec))
    new   1: select * from table(cast(multi_return(7599) as a_rec))
    E_NM                                E_SAL
    BILLY                                4500
    Elapsed: 00:00:00.00
    satyaki>Regards.
    Satyaki De.

  • Can we write leave program syntax in RFC function module.

    hello friends,
       can we write leave program syntax in RFC function module. Iam developing RFC Function module .
    useful answers will be awarded..
    Regards
    Kanth
    Edited by: Kanth on Mar 30, 2008 11:38 PM

    Don't use leave program in RFC function module. You can better use EXIT or RETURN. But when developing RFC modules you should use the return structure BAPIRET2 to store message generated in the calling system. So when you use EXIT or RETURN, first give a message so the calling program knows why the RFC module was exited.

  • Can we write %System.getProperty("CONFIG_MODE");% this stmt in EL or jstl

    Hi everyone,
    Can we write below statement in EL or jstl instead of using Scriplet.
    <%System.getProperty("CONFIG_MODE");%>
    Thanks,
    Nihar.T

    getting a system property is too much on the business logic side. You could create a bean that returns the system property as a member, like:
    public class PropertyBean
    public String getConfigMode()
      return System.getProperty("CONFIG_MODE");
    }then simply use EL in your JSP(s) to get the value from that bean. Of course you could just make the getConfigMode() method part of an existing bean you are using.

  • Exceptions not thrown on interrupted SocketChannel.write()

    I just noticed a behaviour of java.nio.channels.SocketChannel.write() that makes me wonder. If write() blocks(), and the channel is closed during this blocking by another thread, AsynchronousCloseException should be thrown.
    However, in most cases this does not happen in my little test app. If any part of the data passed to write() has already been written to TCP before the socket was closed, write() returns without exception.
    Similar behaviour is observed with intterupting. If the thread blocked in write() is interrupted by another thread, it returns immediately and has the interrupted Flag set, but in most cases no Exception is thrown.
    ClosedByInterruptException is only thrown if not any part of the data passed to write() has been passed to TCP.
    Is this a bug or a feature ?

    Yes, i'm pretty sure that it blocks. In my test, the server just accepts the connection and then goes to sleep for a looooong time. The client just connects, and sends 10Meg of fata in one write() call. If i do not interrupt the client, it blocks as long as the server sleeps. In this case, this is the client's stack while blocking:
    Thread [main] (Suspended)     
         FileDispatcher.write0(FileDescriptor, long, int) line: not available [native method]     
         SocketDispatcher.write(FileDescriptor, long, int) line: 29     
         IOUtil.writeFromNativeBuffer(FileDescriptor, ByteBuffer, long, NativeDispatcher, Object) line: 104     
         IOUtil.write(FileDescriptor, ByteBuffer, long, NativeDispatcher, Object) line: 75     
         SocketChannelImpl.write(ByteBuffer) line: 334     
         Channels.write(WritableByteChannel, ByteBuffer) line: 60     
         Channels.access$000(WritableByteChannel, ByteBuffer) line: 47     
         Channels$1.write(byte[], int, int) line: 134     
         Channels$1(OutputStream).write(byte[]) line: 58     
         SocketClient.main(String[]) line: 75     If i start another thread before calling write(), that closes the socket after 3 seconds, the following happens: The call of IOUtil.write() returns ( with a value n that i cannot see in the debugger ), This value n is tested inside SocketChannelImpl.write() via (n > 0 || (n == IOStatus.UNAVAILABLE), what return true. For that reason, AbstractInterruptibleChannel.end(boolean), does not throw an exception.
    Once the server wakes up later, it is able to read about 200K from the socket...
    I tried this on a linux system (kernel 2.6.17, glibc 2.4) with jdk 1.6.0_03. I'm now gonna try it under windows, hold on..
    Of course, if anybody is interested, i'll post the test proggy...

  • Can't write to station globals in deployed system

    When I run Teststand distribution on the target system, I can’t write to the station globals from my custom application that uses the Teststand engine.  The following are the facts:
    When I run my custom application, my sequence can’t write to any of the station globals.  The function TS_PropertySetValString returns : -2147024890.
    I made sure that my distribution included the sequence editor.  When I run my sequence in the editor, I don’t get any errors AND the fields in the station globals are actually updated with the correct values.
    I have updated all of the users using the “User Viewer” in the sequence editor to make sure that the “Edit Station Globals” and “Grant All” are true.  I have added code to my custom application to query the engine for these flags and display them in a popup, the flags are TRUE.
    I also made sure that the “Check User Privileges” under the “User Manager” in the sequence editor is OFF.  It made no difference
    I am at a total loss.  Any ideas?
    Todd

    Inside my custom application EXE that launches the teststand engine, the following call works:
    tsErrChkMsgPopup(TS_PropertySetValString (m_oGlobals, &errorInfo, "TestConsoleInfo.Operator", 0, sText));
    The above call uses a globals object
    Inside the DLL, that is invoked by the sequence file being executed by my custom application, the following function fails with totally bogus info in the tsiErrorinfo structure.  And yes, the sequence handle is valid because this same sequence handle is used to read from the station globals, we just can't write to the station globals.
    iStatus = TS_PropertySetValBoolean(g_iTSseqHandle, &tsiErrorinfo,
             "StationGlobals.ErrorInfo.CurrentError.Occured",
             0, 1);
    The above call uses a sequence object
    Todd

  • How can I write cursor which tell me no record exists

    Hi Experts,
    I want to know how can I write a cursor which told me no record exists before opening and running the loop.
    So I want that if no record exist then I dont want to run loop and open the cursor.
    Example: cursor c1 is select empno from scott.emp where empno=10
    In procedure body, I want to check if there is no record against my cusor then I don't like to open it.
    Thanks

    Rizwan Ali Wahla wrote:
    I want to know how can I write a cursor which told me no record exists before opening and running the loop.
    So I want that if no record exist then I dont want to run loop and open the cursor.Not possible.
    Example: cursor c1 is select empno from scott.emp where empno=10Single row? No need for an explicit cursor. No need for a loop. It can be done using an implicit cursor. E.g.
    SQL> create or replace function GetEmployee( empID number ) return EMP%RowType is
      2          empRow EMP%RowType;
      3  begin
      4          select
      5                  e.* into empRow
      6          from    emp e
      7          where   e.empno = empID;
      8          return( empRow );
      9  exception when NO_DATA_FOUND then
    10          return( null );
    11  end;
    12  /
    Function created.
    SQL>
    SQL> declare
      2 
      3          procedure ProcessEmp( empID number ) is
      4                  empRow  EMP%RowType;
      5          begin
      6                  empRow := GetEmployee( empID );
      7 
      8                  if empRow.empno is null then
      9                          dbms_output.put_line( 'Employee '||empID||' does not exist.' );
    10                  else
    11                          dbms_output.put_line(
    12                                  'Employee '||empID||' is '||empRow.ename ||
    13                                  ' and employed as '||empRow.job
    14                          );
    15                  end if;
    16          end;
    17 
    18  begin
    19          ProcessEmp( 7900 );
    20          ProcessEmp( 7901 );
    21  end;
    22  /
    Employee 7900 is JAMES and employed as CLERK
    Employee 7901 does not exist.
    PL/SQL procedure successfully completed.
    SQL> All SQLs are cursors. Every single SQL passed to Oracle for parsing and execution is a cursor. So it does not make sense to use one SQL cursor for testing the existence of a specific row, and then another to return the row.
    That kind of logic is PL/SQL logic and a single SQL cursor need to be used.
    PS. Make sure that the SQL projection only includes the columns needed in PL/SQL. If the SQL is a pure exist row? check, then do not return any column and use a literal value as the projected column.
    Edited by: Billy Verreynne on Feb 16, 2012 5:55 AM

Maybe you are looking for

  • Snow Leopard and Lion on external hard drive

    I successfully installed Snow Leopard on an external hard drive in one of the partitions.  I am also able to boot from the Snow Leopard on the partition, access the internet, get my email and have successfully installed Evernote. I am also able to ac

  • Download and upload program

    Hello to everybody, I'm looking for a standard program that can download and upload program' source codes. I found the program REPTRAN (in SAP release 6.0) that can only download the source code (with the include as well), but i didn't find the uploa

  • Additional Field in Vendor Master for PF Number and ESI Number

    Hi Experts, I have to maintain ESI Number and PF Number in Vendor Master, but no such field is available in vendor master or J1ID. Kindly suggest me the fields which I can use. We have to capture the ESI and PF Number of the vendor in case He is a su

  • Error message for iPhoto

    I am receiving a message "You can't open your current photo library using this version of iPhoto." When I try to open iPhoto. It continues to say, "You have made changes to your photo library using a newer version of iPhoto. Please quit and use the l

  • Live view tethering

    Is there a way to use live view while tethering with a Canon EOS 1100D ? The Canon Free EOS Utility does have this functionality. Appstore's Smart Shooter does have it too! Why can't find this in Aperture?