NIO problem: multiple write

Hello.
I am using a NIO server for my application with a pool of WorkingThreads to handle client requests.
The read part seems to work fine (I am deregistering the OP_READ interest when I begin to read from the socketchannel and I register it back when I finish processing the data). This way I am able to process data coming in chunks down the stream.
Now, the problem I have is with writing data back to the client. If I send the data with only 1 socketChannel.write(ByteBuffer) method the client gets it correctly. But if I try to write in a while() loop more messages it happens that the client receives the first chunk correctly but SOMETIMES it receives rubbish as the next chunks. My guess is that after the first write(), the server may send some zeros to the client just before the next chunk so the client interprets that as valid data.
I have tried to unregister the key from writing (key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE))) immediatelly after I've done a write() and reregister it for writing just before I want to send the data but this didn't help. I'm sure this is solvable but I haven't met anywhere code that deals with writing more than 1 buffer (like writing a big file for example).
Any help would be very much appreciated.
Thank you.
Bogdan

Thank you for replying, ejp, but it seems that what you said is not quite true. Here is my send method:
public void send(SelectionKey key) {
     try {
          if (sendMessages.size() != 0) {
               String message = null;
               while (sendMessages.size() > 0) {
                    synchronized (sendMessages) {
                         message = (String) sendMessages.removeFirst();
                    ByteBuffer theBuffer = ByteBuffer.wrap(message.getBytes());
                    theBuffer.put(message.getBytes());
                    theBuffer.flip();
                    ((SocketChannel) key.channel()).write(theBuffer);
                    theBuffer.flip();
                    log.debug("Sent message:" + decoder.decode(theBuffer));
          key.interestOps(key.interestOps() | SelectionKey.OP_READ);
          key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
     } catch (IOException e) {
          key.cancel();
}I verify what I send by outputting with the line log.debug("Sent message:" + decoder.decode(theBuffer));The messages are strings which are being taken from a LinkedList. The chunks I'm sending are of size 4096 bytes.
I forgot to mention that the client uses simple IO (blocking mode). In between the sendings from the server it receives zeros and considers them as part of the message.
I am using Windows 2000 + JDK 1.4.2_01

Similar Messages

  • NIO Problem

    I had a NIO problem.
    I tried to open a socket channel, and grep a HTML page from HTTP GET.
    I did it success if I open and close socket channel everytime I send a
    request and get the response.
    However, if I keep open the socket channel and send multiple requests,
    I'll get IOException.
    Does anybody know how to solve this problem? Thanks in advance!
    Note: I don't want to fire requests in parallel but one by one
    sample code:
    =============================================================
    private Charset charset = Charset.forName("ISO-8859-1");
    private SocketChannel channel;
    try
    // do connection
    InetSocketAddress socketAddress =
    new InetSocketAddress( "www.mydomain.com", 80);
    channel = SocketChannel.open(socketAddress);
    // send request #1
    channel.write(charset.encode("GET /page1.html HTTP/1.0\r\n\r\n") );
    // read response #1
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    while ((channel.read(buffer)) != -1)
    buffer.flip();
    System.out.println(charset.decode(buffer));
    buffer.clear();
    // send request #2
    channel.write(charset.encode("GET /page2.html HTTP/1.0\r\n\r\n") );
    // read response #2
    // program threw "java.io.IOException: Read failed" error
    while ((channel.read(buffer)) != -1)
    buffer.flip();
    System.out.println(charset.decode(buffer));
    buffer.clear();
    catch (IOException e)
    e.printStackTrace();
    finally
    if (channel != null)
    try
    channel.close();
    } catch (IOException e) {}
    =============================================================

    I am pretty sure that most webservers only do one request per connection by default. Try looking up some information on HTTP request headers. I am pretty sure there is a header that you need to send to the server to let the server know that you want to do multiple requests with the same connection. I believe the header is called 'keep alive' or some other such thing.
    I'm not an expert on http, so I can't help you any further that that.

  • Multiple writes possible in DS in labview but not in CVI?

    Hi
    Am using Datasocket to communicate between to VI's, In one of the VI's am opening a new dataitem in "readwrite" mode and doing both read and write operation, and in the other VI am just writing on the dataitem by supplying the URL to the write function, surprisingly this is possible even though i havent created the dataitem from DS manager and have not selected the option of "allow multiple writes".
    But if am creating a CVI application, which opens the dataitem in "readwrite" mode, and if i write on that dataitem from labview, it gives me an error, i even tried selecting the "allow multiple write" on this dataitem.
    Please suggest some solution. Also if i open a lot of Dataitems will it cause any problems?, i guess our project needs atleast 100 dataitems if i will have to use command and response in different dataitems.
    thanx for the help
    Arun

    Hello,
    The following Knowledge Base describes two possible soltions for this issue.
    Why Does My DataSocket Connection in LabVIEW Fail with "Error: Can't connect to data item, another w...
    The second solution is what you have already described with checking the box to Allow Multiple Writers. I am not sure why that is not working in your case, but I would suggest trying the first soltuion suggested in the KB. It involves creating the datasocket item a certain way in LabVIEW, and more details are available in the KB.
    Scott Y
    NI

  • Problem in write content in excel

    Hi All,
    Please help to resolve the problem while write the content in the excel.
    By reading the cursor we get the data, then iterate the value and append in the stringbuilder(data is single record about the user access permission) each record is differentiate by adding new line character. After append the data in stringbuilder, using Filewriter create a .csv file
    code
    writer = new BufferedWriter(new FileWriter(strDestinationFilePath.trim()));
    writer.write( strFileContent.toString() );
    it create the .csv file. when i try to open file it shows following message
    File not loaded completely
    when i click show details button, it show message as
    This error is usually encountered when an attempt to open a file with more than 65,536 rows or 256 columns is made. Excel is limited to 65,536 rows of data and 256 columns per worksheet. You can have many worksheets with this number of rows and columns, but they are usually capable of fitting into one workbook (file). The number of worksheets you can have per workbook is limited only by the amount of available memory your system has. By default, Excel can manage 3 worksheets, more if there is available memory to support the quantity of data.
    Truncation of rows or columns in excess of the limit is automatic and is not configurable. This issue can usually be remedied by opening the source file with a text editor, such as Microsoft Office Word, and then saving the file off into
    Edited by: sunRP on Nov 18, 2009 10:16 PM

    says it all, really...
    I wonder why you think we can help you if you can't even understand that highly detailed error message which tells you EXACTLY what the problem is.

  • I am having some problem to write র্যা (ro-a jofola akar) in indesign

    I am having some problem to write র্যা in indesign... I am not being able to write it there, where as it's possible in MS word. Can anyone suggest me what to do?

    Ar you using a font that has the required glyphs? Do you have the correct language assigned to the text (language is a character-level attribute, it is NOT set by choosing a dictionary in the prefs)? Is one of the World Ready composers turned on?
    What is happening when you try?

  • Should I use DB_INIT_CDB while open DB_ENV(multiple writer and reader)?

    My version is db-4.7.25.NC
    I want to use BDB as backend for BBS, so multiple writer and multiple reader are not avoidable.
    My question is what flags I should select while open DB_ENV and DB, DB_THREAD or else?
    DB_INIT_CDB can support only writer thread, I wonder it could meet my requirement?
    Any suggestion, welcom!
    Edited by: user11335524 on Jun 30, 2009 11:37 PM

    The <tt>DB_INIT_CDB</tt> flag only permits one writer <i>at a time</i>. Berkeley DB uses locking internally to enforce this constraint, so if two application threads try to update at the same time, one of them will wait for the other. The <tt>DB_THREAD</tt> flag is required if multiple threads will share the same <tt>DB_ENV</tt> or <tt>DB</tt> handle.
    Regards,
    Michael Cahill, Oracle Berkeley DB.

  • NIO SocketChannel truncating write from MappedByteBuffer

    Hello!
    I'm running SDK build 1.4.1_01-b01 on Win2K (SP3), but I can also duplicate this on Linux (2.4 kernel).
    I'm writing a simple file server, and it uses the following code:FileInputStream fis = new FileInputStream(file);
    FileChannel fc = fis.getChannel();
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    sc.write(buffer);
    sc.close()However applications that download (not just Java applications) do not receive the entire file. The server reports sending all of the bytes (sc.write() returns the value from fc.size()) but it is not all received byt the client downloading (I'm using wget on a Linux box).
    NIO has no way to flush, so... ok this is where I'm lost. Am I doing this all wrong?
    I even triedsc.socket().getOutputStream().flush();to no avail.
    Another similar example of this problem is the code from this article at JavaWorld:
    http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html
    The zip file contains only one class file that runs, except serving up say a 300kB Jar file does not work.

    Firstly thankyou very much for your time so far...
    I hope I'm not tripping over the protocol, I have implemented a simple HTTP server.
    The important section of code (very cut down - no log messages and less Exception handling) is:public class HttpGetHandler extends Thread {
        private SocketChannel sc;
        private File file;
        public HttpGetHandler_1(SocketChannel pSocketChannel, File pFile) {
            super("HttpGetHandler");
            this.sc = pSocketChannel;
            this.file = pFile;
            start();
        public void run() {
            try {
                // Open the file and then get a channel from the stream
                FileInputStream fis = new FileInputStream(file);
                FileChannel fc = fis.getChannel();
                // Get the file's size and then map it into memory
                long sz = (int) fc.size();
                // Create Header
                String header = new String(
                "HTTP/1.0 200 OK\r\n"
                + "Content-Length: " + sz + "\r\n"
                transmitBuffer(ByteBuffer.wrap(header.getBytes()));
                long position = 0;
                while (position < sz) {
                    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, position, sz - position);
                    transmitBuffer(buffer);
                    position += buffer.capacity();
            } catch (Exception e) {
            } finally {
                try {
                    // HACK
                    try {
                        Thread.currentThread().sleep(20000);
                    } catch (InterruptedException e) {
                        log.warn("InterruptedException", e);
                    sc.close();
                } catch (IOException e) {
        private void transmitBuffer(ByteBuffer pBuffer) throws IOException {
            while (pBuffer.hasRemaining()) {
                sc.write(pBuffer);
    }

  • Socket NIO Problems

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

    I'm not sure that a key will ever return with more than one operation bit selected. I expect that the selector simply puts the key into the selected set as soon as it sees any one of the interestedOps that match the current state.
    The general problem you are having, it seems, is that isWritable(), in many cases, will constantly return true for a low volume socket. This being the case, the only solution I see is to either deal with output with blocking calls or to dynamically change your interestedOps when there is data to write. That's what I did. I don't know yet how well it will scale. This is certainly not a bug, the application must deal with it. Perhaps it would be nice to have some kind of interface, like "SelectionKeyAttachment" and have the SelectionKey.attach() method take one of those. The SelectionKeyAttachment interface could implement something like isWritable(), isReadable(), isAcceptable() so that the Selector can also invoke the callback before putting it into the selected set. I haven't really thought this through, just initial thoughts.

  • Massive IMAP problem, multiple iPhones - constant spinning wheel

    A friend has had problems using email on his iPhone since he got it, and now after a couple of months of no problems, mine has started doing the same thing.
    The problem started for him on a UK 1.1.2 firmware iPhone with an IMAP account. If you start from scratch, manually setup an IMAP account, it will connect and get your messages. However later, you will find that the iPhone email program is constantly showing the spinning wheel at the top of the screen (showing activity), not the symbol at the bottom of the screen. Worse, the battery rapidly runs down (because it is doing constant data transfers), and worse new emails do not reliably get through. This happens whether you are using GPRS, EDGE, or WiFi (does not make a difference). This problem still happens with 1.1.3 firmware. There is so much data transfer happening (or trying to happen) that the phone actually gets quite warm.
    This week after a couple of months of owning my own iPhone with 1.1.3 firmware has also started doing the same thing. My main IMAP account is on a totally different server, running a different server application to my friends. However it also seems to happen with GMail accounts (using IMAP).
    I am currently at home and I can see my WiFi (AirPort Extreme) base-station showing lots of activity and I know that no other WiFi devices are active so it is purely the iPhone. Turning off the email account stops the problem (and I can then see the WiFi activity stop as well) but that is hardly a solution. Also setting it to manual polling for email helps but again is not a proper solution. It is so bad that sending emails is very difficult as well.
    Even though at the iPhone end nothing seems to be coming through, one can see the iPhone as a connected user at the server end (I have access to the servers, obviously not for Gmail though).
    My friend has swapped his phone four times at the Apple Store and still has the problem, and as I said mine has started as well. Turning off and on does not help, resetting network settings does not help.
    Apple Mail on a Mac (running both Leopard and Tiger), and other IMAP clients have no problems with the same IMAP accounts (for both of us).
    Other Internet access like Web, Stock Widget, Weather Widget, even the iTunes WiFi store work fine. It is just email that is broken.

    Pdobry wrote:
    The problem is that Mail app in iPhone is trying to download message headers via FETCH command and does not handle properly response from IMAP server which does not support partial download of email headers. It starts asking for the headers in the infinite loop which quickly drains out the battery
    More recent testing by myself reveals it is getting stuck on some messages when doing the 'message peek' to get the summary of an email. It gets the subjects fine (as the first pass) but then gets stuck on some emails when doing the second pass to get the summary. Apple Mail on a Mac does not (as far as I am aware) do a message peek so does not have this problem.
    The two different makes of server I have seen this problem with do support this message peek command in that at least some of the time it is working with the iPhone.
    I was able to get a debug level log which shows entries like this
    \[02/Apr/2008 23:56:17\]\[48699904\] {imaps} Peek FETCH executed on message 0000ba58 in folder [email protected]/INBOX
    \[02/Apr/2008 23:56:17\]\[48699904\] {imaps} Sent 1 fetch responses
    \[02/Apr/2008 23:56:18\]\[48699904\] {imaps} Command 293 UID FETCH 47704 BODY.PEEK\[2.HEADER\]<1177.15207>
    \[02/Apr/2008 23:56:18\]\[48699904\] {imaps} Peek FETCH executed on message 0000ba58 in folder [email protected]/INBOX
    \[02/Apr/2008 23:56:18\]\[48699904\] {imaps} Sent 1 fetch responses
    \[02/Apr/2008 23:56:18\]\[48699904\] {imaps} Command 294 UID FETCH 47704 BODY.PEEK\[2.HEADER\]<1177.15207>
    The above shows two repetitions but it keeps on (and on, and on). Other occasions show this does work for other messages. If I deliberately arrange to get the iPhone to connect to get the latest messages I can see it get stuck on a particular message, and then even if I turn it off and back on and reconnect it will get stuck on the same message. If repeated on a later date then the contents of the inbox will have changed and the message it gets stuck on will be different.
    As it seems to be linked to specific messages it was not a surprise that when this is tried on a practically empty email account the problem does not occur.
    This has happened with multiple different makes of mail server (well at least two), multiple email accounts, multiple users, and multiple different iPhones (one person had his swapped four times). It does not happen with 'ordinary' IMAP client software, only with the iPhone.
    Even if one for arguments sake assumes the mail server is at fault and is sending the iPhone garbage, the iPhone should only try a single specific email a maximum number of times (for example five), and then give up. This would prevent it draining the battery so fast and trying to cook itself (by constantly running its transmitter).

  • Problem:Multiple instances of the same applet on a webpage...

    I have an applet which connects to a server to read an XML-file.
    I use Doucument to parse the XML-file like this:
    String xmlurl="http://www.somesite.com/somexmlpage.php";
    Document d =DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlurl);
    (...read the XML-file...)
    This works fine.
    However, I need multiple instances of the same applet running at the same time on the same webpage.
    Now, with multiple applets running at the same time the parsing no loger works. If one applet is doing some parsing and a taskswitch takes place to let another applet run, the applet which is interrupted is not able to continue the parsing as it looses its "incoming data" when another applet reads from the server.
    How can different applets affect each other like this?
    And how can I fix the problem?
    Thanks in advance for any help!!

    However, I need multiple instances of the same applet running at the same time on the same webpage.
    Why? But okay.Because the the different applets show information about different items.
    Now, with multiple applets running at the same time the parsing no loger works. If one applet is doing some parsing and a
    taskswitch takes place to let another applet run, the applet which is interrupted is not able to continue the
    parsing as it looses its "incoming data" when another applet reads from the server.
    How did you determine that's what's happening?By printing out debuginformation.
    Each applet prints out a message (System.out.println) when it creates an instance of Document (ie. connects to the server) and the applet also prints out XML-information as the XML-file is processed.
    But, actually, I was a bit quick in my first post; The applet doesen't neccesarily loose its "incoming data", but the parser looses the data it is parsing. I can download the data from the server first, and then start parsing it. If a taskswitch happens while one applet is parsing, it looses its data, even if the data is allready downloaded.
    I see this since I see another applet making a printout, and when first applet starts again, the parser has lost track of its data.
    It works fine if only one applet is running. And everything is fine until the next applets starts; I can see this from the printout.
    Again, the appet prints out data as it parses the document. I see the next applet starting to work, and when the first one continues parsing again the printout shows that data is no longer there. It happens everytime the runtime switches to another applet, and it never happens if just one applet is running.
    Googeling a little tells me that DocumentBuilder.parse() isn't thread-safe, but this shouldn't have anything to do with it, should it?
    Each applet is a separate process, and not different threads in the same process, aren't they? (Not sure how the runtime treats multiple applets...)And secondly, the applets create their own instance of Document anyways.

  • Problem Multiple record navigation in oracle forms

    I retrieve multiple records using cursor fetch command in the select query i have given condition to retrieve details of employee no.
    For example if we are giving an input as empno:100 then it retrieves two records of same emp no(100).It displays 2/3 records in the task bar when i navigate using push buttons it displays an empty record in the interface provided.(ie 3/3 records).How to avoid third unknown record displaying in the interface.

    most likely the problem is during the population of the block using the query.
    i assume that you are creating one additional record after the last record from your query..
    so this must be either with the CREATE_RECORD or NEXT_RECORD problem in the loop.so you should check in the loop first if the record exists, then do CREATE_RECORD or NEXT_RECORD.

  • Servlet I/O Stream problem: cannot write into file, error 500

    I am a new Java developer and now, I am facing a problem regarding the error 500. I try to grab records from a table with a date as a constraint. There are two servlets involed: a) saveRecord and b) getRecord. Servlet getRecord will grab data from a database while another servlet, saveRecord will get the data from servlet getRecord and save it into a file. The codes are as below:
    =========================================================================================================================================
    // Servlet Name : saveRecord
    BufferedInputStream instr     = null;
    BufferedOutputStream outstr     = null;
    PostMethod http_post          = null;
    http_post = new PostMethod("getRecord");
    http_client.executeMethod(http_post);
    instr     = new BufferedInputStream(http_post.getResponseBodyAsStream());
    outstr     = new BufferedOutputStream(new FileOutputStream("c:\student.csv"), false));
    int byte_at;
    while (-1 != (byte_at = instr.read())) {
         outstr.write(byte_at);
    =========================================================================================================================================
    // Servlet Name : getRecord
    ServletOutputStream out     = response.getOutputStream();
    StringBuffer str_buf     = new StringBuffer();
    str_buf = generateStudentAc();
    out = response.getOutputStream();
    FileStream(out, response, str_buf);
    // Function Called
    private StringBuffer generateStudentAc() {
         StringBuffer str_buf = new StringBuffer();
         String date = "2000-01-01";
         statement = connection.createStatement();
         resultset = statement.executeQuery("SELECT NAME, ADDRESS FROM STUDENT WHERE DATE>'" + date + "';
         // Write column headers               
    str_buf.append("NAME,ADDRESS");
    String data_row;
    while (resultset.next()) {
              data_row = "\n";
              data_row += "\"" + resultset.getString("STUDENT") + "\"";
              data_row += ",\"" + resultset.getString("ADDRESS") + "\"";
              // Write row
              str_buf.append(data_row);
         return str_buf;
    // Function called
    private void FileStream(ServletOutputStream out, HttpServletResponse response, StringBuffer str_buf) {
         BufferedOutputStream buf_out = null;
    // Create input/output streams
         buf_out     = new BufferedOutputStream(out);
         int length     = str_buf.length();
         // Read/Write
         for (int i = 0; i < length; i++) {
              buf_out.write(str_buf.charAt(i));
    =========================================================================================================================================
    Then, the result will be post back to a JSP page. It didn't work when the records in database growing bigger ( > 100 000 records) but works nice while the records are still in a small quantities ( < 20 000 records). It seems that no record can be inserted into the file and the JSP page becomes blank. When I opened the csv file, I found a message"Error 500:" inside it.
    Hope you all experts can help to figure out this problem. TQ

    I am amatuer in Java Programming, so I don't know how to implement serializable interface but I will look through it.
    However, as I mention before, the code run perfectly if there are not much records un the table. But once there are more and more table added in (> 1000 000 records) in the table, it becomes unstable - sometime it works but most of the time it doesn't. So, I didn't find any different event I replaced the code with String date = "=2000-01-01".
    Anyway, thanks for your help.

  • Problem - Multiple recordsets in one page

    Hi,
    Is it possible to use more than 1 recordset in a single page?
    Dreamweaver acts like there should be no problem, but when I upload
    & test the page I just get an error message saying there's a
    problem processing the requested URL. Each table and field has a
    unique name. I'm using ASP VBScript on Win2000 with Access DB.
    Please help!
    Ian

    The simple answer is yes, multiple recordsets are OK. I'd
    suggest re-posting - explaining what you're trying to do, what the
    errors say and supplying code or a URL so people can see what
    you're doing.

  • NIO problems.

    We have developed a NIO C/S server, the client side is pluged into Tomcat.
    We have encounted an out memory exception in tomcat, and dump the tomcat, and find NIO Client thread is blocked. Is the block normal? or its some bugs?
    "Thread-2862" daemon prio=5 tid=0x00dabf60 nid=0x35dd runnable [ce481000..ce4819c8]
    at sun.nio.ch.DevPollArrayWrapper.poll0(Native Method)
    at sun.nio.ch.DevPollArrayWrapper.poll(DevPollArrayWrapper.java:136)
    at sun.nio.ch.DevPollSelectorImpl.doSelect(DevPollSelectorImpl.java:70)
    at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:59)
    - locked <0xf1b373d8> (a java.util.HashSet)
    - locked <0xf1b37460> (a java.util.HashSet)
    - locked <0xf1b37308> (a sun.nio.ch.DevPollSelectorImpl)
    at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:70)
    at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:74)
    at com.televigation.databus.io.SelectorThread.run(SelectorThread.java:429)
    at java.lang.Thread.run(Thread.java:534)

    Thank you for your concern, the problem for the "POST " method is solved ( the request was constructed in a wrong way), but I'm still facing the zero problem , I have three cases which I receive zero bytes from the server:
    1. The last chunk, in this case I received the whole responce correctly and this indicates the end of stream
    2. I received some of the response and when I register into the selector to read again I got another chunk till I receive the whole response.
    3. This is the actuall problem, I receive zero bytes and register for read again I got nothing and this key remains into the selector !! with no other chunks , and I didn't receive the whole response correctly !!!!
    Thanks again

  • Problem with Writer.flush() appending extra character

    I have written a simple file copy that does the following:
         public static void copy(File source, File dest) throws IOException
              FileReader fr = new FileReader(source);
              FileWriter fw = new FileWriter(dest);
              try
                   char[] ch = new char[(int)source.length()];
                   fr.read(ch);
                   fw.write(ch);
              finally
                   fr.close();
                   fw.close();
    It works fine, and has done for some time.
    For some reason, in a recent data collection, I have 3 files out of about a hundred, where the following behaviour occurs.
    The char array is written to the file fine. For some reason when fw.flush() is called (i have tested this and confirmed that it is the call to flush() that is causing it) it appends a char to the end of the file with a value of -1.
    This is causing merry havoc with my XML parser.
    Can anybody tell me how to stop Writer from adding a -1 to my file?
    This is on java 1.4.2 currently.

                   char[] ch = new char[(int)source.length()];File.length() returns the number of bytes in the file.
    However, you're loading that file via a Reader, which converts those bytes into characters using some encoding method. Depending on the encoding, the number of characters produced may be completely different from the number of bytes read. It's also possible that the bytes read are not valid with the encoding.
    If you're just copying files, use FileInputStream and FileOutputStream. Better, download the Jakarta Commons IO library, and use their already-tested methods.
    If you're working with a JAXP XML parser (ie, what comes with JDK 1.4 and above), create your InputSource from a FileInputStream. That will let the XML parser use the encoding specified in the file, ignoring whatever your JRE's default encoding is.
    If you're planning to work with the raw text, then you're going to have to learn about character encodings. I don't have a tutorial link handy, so either Google for one or start with the documentation for java.nio.charset.Charset.

Maybe you are looking for