Catch client disconnect without sending data?

I am writing a Java Servlet and I need to know if the client has disconnected (pushed the stop button, closed the browser, etc) without sending data. Basically, I need to call socket.isOutputShutdown() on the connected socket. However, the Java Servlet interface does not provide access to the socket, only the socket's output stream. In the book Java Servlet Programming (2nd edition) by Jason Hunter, page 159 suggests attempting to write a single space and then catching the resulting error. This works fine for HTML, but my servlet is not guaranteed to be sending HTML. It could be sending a file, in which case miscellaneous "ping" spaces would corrupt it.
Is there a way to check if the client has disconnected without sending "ping" data from a servlet?
Thanks,
Nathan Lewis
P.S. I thought I posted this a couple days ago, but I can't find it now.

This appears to be very close, but I don't think it'll work. I want to know if/when the client hits the stop button on their browser (or otherwise closes the TCP socket). The Unbound event only occurs if:
1. The session times out
2. The user reloads the page. (Then Unbound is immediately followed by a Bound event)
However, an Unbound event doesn't seem to be occuring if the user hits stop. It doesn't occur until the session times out. If I set the session timeout interval to something short, the Unbound even is occuring even though the client is still connected! This happens with the servlet container I'm using, as well as TomCat 3.3.

Similar Messages

  • How to print html file on client system without viewing data on client syst

    I want to print html data from database.
    i am not able to print it using java code,
    javascript can do that.
    but in javascript window is opened on client browser.
    but i dont want to open that
    var disp_setting="toolbar=no,location=no,directories=no,menubar=no,";
           disp_setting+="scrollbars=no,width=0,height=0";
         var docprint = window.open("","",disp_setting);
         //docprint = new PopUpWindow() ;
         docprint.document.write('<%= mm %>');
         docprint.document.close();
            docprint.focus();
         docprint.document = null; mm contents the data to be printed. it prints well but window is shown
    in mm there is <BODY self.print() > so it prints on printer but i am viewing window i donot want to view window....
    and print Dialog box also.. I want to by pass this both.
    please send me code or any help regarding that.
    ....

    1. Post a javascript question on a javascript forum please.
    2. Don't think you can bypass without some plugin/setting on the client browser.

  • SSLsocket client can't send data...

    I know the problem is at the client side because i tested the server with openssl and worked without a problem.
    It seems the client connects to the server, but the server never recieves this - pw.print("State: 2");
    What i'm doing wrong?
    Client:
    new Thread(new Runnable() {
    public void run() {
                    try {
                        // Get Socket factory
                        SocketFactory factory = SSLSocketFactory.getDefault();
                        // Get Socket from factory
                        Socket s = factory.createSocket("localhost", 8254);
                        // Send request
                        OutputStream os = s.getOutputStream();
                        pw = new PrintWriter(os);
                        // Setup command
                        pw.print("State: 2");
                        pw.flush();
                        // Get response
                        InputStream is = s.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                    } catch (Exception exception) {
                        exception.printStackTrace();
    public static void main(String args[]) {
            //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            try {
                System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
                clientKeyStore = KeyStore.getInstance("JKS", "SUN");
                cksPass = "superstar".toCharArray();
                ctsPass = "superstar".toCharArray();
                clientKeyStore.load(new FileInputStream("client.ks"), cksPass);
                clientTrustStore = KeyStore.getInstance("JKS", "SUN");
                clientTrustStore.load(new FileInputStream("client.ts"), ctsPass);
                kmf = KeyManagerFactory.getInstance("SUNX509");
                tmf = TrustManagerFactory.getInstance("SUNX509");
                kmf.init(clientKeyStore, cksPass);
                tmf.init(clientTrustStore);
                sc = SSLContext.getInstance("TLS");
                sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sRand);
            } catch (Exception e) {
                e.printStackTrace();
            }.........Thank You for any help.

    pw.print() doesn't send a newline.
    If the server is using readLine() it is waiting for a newline.
    If you never send a newline the server will never get out of readLine().
    So, send a newline. Use pw.println().

  • Client copy without tranasactional data

    Hi
    We are performing a local client copy from client 321 to 330.  We need only Master data and Customizing but not Transactional data.  Do we need to use the profile SAP_UCUS?? or any other profile?
    Thanks
    Minhaj

    Hi Ruchit,
    Thanks for the quick response again.
    As said only users will be moved from master data not all other data.  What data will be left behind and whats the process of migrating it?
    Thanks in advance
    Minhaj

  • Error 61 when sending data from client and back from server.vi

    Trying to generate and send a data from client.vi and adding the numbers generated and sending it back to the client .In client the data is received only once and an error 61 occurs .How do I get rid of this error?I have attached the two files for reference
    Attachments:
    Sguruserver.vi ‏63 KB
    client1.vi ‏100 KB

    You can certainly use and application started by WebStart to send data to a server.
    However, the Sandbox restrictions allow you to contact the server the application was loaded from without asking for permission first (i.e. signing your application and requesting the proper permissions in your JNLP file).
    The JNLP BasicService can be used to retrieve the URL (and therefore the server) the application was loaded from.

  • Problem sending data with HTTPS  using client authentication.

    Hi,
    I�m tryingto send a message to a secure server using for this client certificate, apparently if I make a GET of "/" (server root) , everything works fine (authentication, and data received), from the moment that I try to ways send data to the "/pvtn " directory i obtain the following error.
    This is a sample of the code i�m using:
    import com.sun.net.ssl.KeyManagerFactory;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.Socket;
    import java.security.*;
    import java.security.GeneralSecurityException;
    import java.security.Principal;
    import java.security.PublicKey;
    import java.util.Collection;
    import java.util.Date;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    import javax.security.cert.*;
    import javax.security.cert.X509Certificate;
    public class Test
    public static final String TARGET_HTTPS_SERVER = "mymachine.mydomain.pt";
    public static final int TARGET_HTTPS_PORT = 443;
    public static void main(String[] args) throws Exception
    System.setProperty("javax.net.ssl.trustStore","/certificados/truststore.txt");
    System.setProperty("javax.net.ssl.trustStorePassword","trustpwd");
    System.setProperty("javax.net.ssl.keyStore","/certificados/truststore.txt");
    System.setProperty("javax.net.ssl.keyStorePassword","trustpwd");
    java.security.Security.removeProvider("SunJSSE");
    java.security.Security.insertProviderAt(new com.sun.net.ssl.internal.ssl.Provider(),2);
    KeyManagerFactory kmf= KeyManagerFactory.getInstance("SunX509", "SunJSSE") ;
    //Socket
    SSLSocket jsslSoc = (SSLSocket) SSLSocketFactory.getDefault().createSocket(TARGET_HTTPS_SERVER, TARGET_HTTPS_PORT);
    String [] ciphers = jsslSoc.getSupportedCipherSuites() ;
    //// Select the ciphers you want and put them.
    //// Here we will put all availabel ciphers
    jsslSoc.setEnabledCipherSuites(ciphers);
    //// We are creating socket in client mode
    jsslSoc.setUseClientMode(true);
    //// Do SSL handshake
    jsslSoc.startHandshake();
    // Print negotiated cipher
    System.out.println("Negotiated Cipher Suite: " + jsslSoc.getSession().getCipherSuite());
    System.out.println("");
    X509Certificate[] peerCerts = ((javax.net.ssl.SSLSocket)jsslSoc).getSession().getPeerCertificateChain();
    if (peerCerts != null)
    System.out.println("Printing server information:");
    for(int i =0; i < peerCerts.length; i++)
    System.out.println("Peer Certificate ["+i+"] Information:");
    System.out.println("- Subject: " + peerCerts.getSubjectDN().getName());
    System.out.println("- Issuer: " + peerCerts[i].getIssuerDN().getName());
    System.out.println("- Version: " + peerCerts[i].getVersion());
    System.out.println("- Start Time: " + peerCerts[i].getNotBefore().toString());
    System.out.println("- End Time: " + peerCerts[i].getNotAfter().toString());
    System.out.println("- Signature Algorithm: " + peerCerts[i].getSigAlgName());
    System.out.println("- Serial Number: " + peerCerts[i].getSerialNumber());
    else
    System.out.println("Failed to get peer certificates");
    try
    Writer out = new OutputStreamWriter(jsslSoc.getOutputStream(), "ISO-8859-1");
    //THIS WAY WORKS FINE
    out.write("GET / HTTP/1.1\r\n");
    // HERE COMES THE TROUBLES
    //out.write("GET /pvtn?someparameter=paramvalue HTTP/1.1\r\n");
    out.write("Host: " + TARGET_HTTPS_SERVER + ":" + TARGET_HTTPS_PORT + "\r\n");
    out.write("Proxy-Connection: Keep-Alive\r\n");
    out.write("User-Agent: SSL-TEST \r\n");
    out.write("\r\n");
    out.flush();
    BufferedReader in = new BufferedReader(new InputStreamReader(jsslSoc.getInputStream(), "ISO-8859-1"));
    String line = null;
    while ((line = in.readLine()) != null)
    System.out.println(line);
    finally
    jsslSoc.close();
    the ssl log until sending the GET is
    main, WRITE: SSL v3.1 Handshake, length = 36
    main, READ: SSL v3.1 Change Cipher Spec, length = 1
    main, READ: SSL v3.1 Handshake, length = 36
    Plaintext after DECRYPTION: len = 36
    0000: 14 00 00 0C 71 AB 40 CC 6C 33 92 05 E9 69 4B 8F [email protected].
    0010: D1 77 3F 6E 3C DB F0 A0 B7 9C CF 49 B6 6D C8 17 .w?n<......I.m..
    0020: 7E 03 52 14 ..R.
    *** Finished, v3.1
    verify_data: { 113, 171, 64, 204, 108, 51, 146, 5, 233, 105, 75, 143 }
    %% Cached client session: [Session-1, SSL_RSA_WITH_RC4_128_SHA]
    [read] MD5 and SHA1 hashes: len = 16
    0000: 14 00 00 0C 71 AB 40 CC 6C 33 92 05 E9 69 4B 8F [email protected].
    Negotiated Cipher Suite: SSL_RSA_WITH_RC4_128_SHA
    When i send the GET
    Plaintext before ENCRYPTION: len = 247
    0000: 47 45 54 20 2F 70 76 74 6E 3F 41 30 33 30 3D 4D GET /pvtn?A030=M
    main, WRITE: SSL v3.1 Application Data, length = 247
    main, READ: SSL v3.1 Handshake, length = 24
    Plaintext after DECRYPTION: len = 24
    *** HelloRequest (empty)
    %% Client cached [Session-1, SSL_RSA_WITH_RC4_128_SHA]
    %% Try resuming [Session-1, SSL_RSA_WITH_RC4_128_SHA] from port 3535
    *** ClientHello, v3.1
    RandomCookie: GMT: 1131988975 bytes = { 45, 113, 241, 212, 81, 255, 244, 169, 74, 41, 160, 227, 197, 210, 155, 211, 47, 237, 18, 179, 238, 47, 28, 86, 30, 253, 157, 253 }
    Session ID: {208, 18, 243, 174, 216, 156, 80, 201, 121, 136, 63, 162, 31, 196, 186, 95, 193, 143, 238, 172, 173, 79, 64, 219, 17, 149, 14, 138, 53, 95, 18, 96}
    Cipher Suites: { 0, 5, 0, 4, 0, 9, 0, 10, 0, 18, 0, 19, 0, 3, 0, 17, 0, 2, 0, 1, 0, 24, 0, 26, 0, 27, 0, 23, 0, 25 }
    Compression Methods: { 0 }
    [write] MD5 and SHA1 hashes: len = 105
    Plaintext before ENCRYPTION: len = 125
    main, WRITE: SSL v3.1 Handshake, length = 125
    main, READ: SSL v3.1 Handshake, length = 94
    Plaintext after DECRYPTION: len = 94
    *** ServerHello, v3.1
    RandomCookie: GMT: 1131991620 bytes = { 205, 194, 212, 113, 37, 213, 41, 13, 60, 142, 135, 68, 17, 78, 227, 251, 176, 211, 133, 203, 153, 173, 153, 195, 93, 7, 87, 123 }
    Session ID: {108, 85, 45, 208, 104, 124, 209, 24, 247, 113, 156, 134, 28, 154, 75, 198, 64, 181, 167, 9, 149, 223, 162, 21, 225, 32, 168, 31, 190, 48, 241, 195}
    Cipher Suite: { 0, 5 }
    Compression Method: 0
    %% Created: [Session-2, SSL_RSA_WITH_RC4_128_SHA]
    ** SSL_RSA_WITH_RC4_128_SHA
    [read] MD5 and SHA1 hashes: len = 74
    main, READ: SSL v3.1 Handshake, length = 3154
    Plaintext after DECRYPTION: len = 3154
    *** Certificate chain
    stop on trusted cert: [
    Version: V1
    Subject: CN=GTE CyberTrust Global Root, OU="GTE CyberTrust Solutions, Inc.", O=GTE Corporation, C=US
    Algorithm: [MD5withRSA]
    Signature:
    [read] MD5 and SHA1 hashes: len = 3134
    main, READ: SSL v3.1 Handshake, length = 479
    Plaintext after DECRYPTION: len = 479
    *** CertificateRequest
    Cert Types: RSA, DSS,
    Cert Authorities:
    [read] MD5 and SHA1 hashes: len = 455
    *** ServerHelloDone
    [read] MD5 and SHA1 hashes: len = 4
    0000: 0E 00 00 00 ....
    *** Certificate chain
    *** ClientKeyExchange, RSA PreMasterSecret, v3.1
    Random Secret: { 3, 1, 19, 223, 230, 65, 59, 210, 10, 69, 239, 178, 185, 5, 52, 57, 44, 160, 163, 239, 85, 64, 173, 16, 132, 234, 33, 228, 0, 8, 134, 52, 20, 190, 196, 15, 205, 35, 169, 39, 14, 160, 143, 74, 210, 74, 43, 181 }
    [write] MD5 and SHA1 hashes: len = 141
    Plaintext before ENCRYPTION: len = 161
    main, WRITE: SSL v3.1 Handshake, length = 161
    SESSION KEYGEN:
    PreMaster Secret:
    .CONNECTION KEYGEN:
    Client Nonce:
    Server Nonce:
    Master Secret:
    Client MAC write Secret:
    Server MAC write Secret:
    Client write key:
    Server write key:
    0000: FE 94 DF 4C 1A 9F FA CE 0C E9 A6 DB 31 53 E5 FD ...L........1S..
    ... no IV for cipher
    Plaintext before ENCRYPTION: len = 21
    0000: 01 0D 16 E6 49 18 36 AF E1 52 9C 2F 72 EE CA DF ....I.6..R./r...
    0010: 41 71 68 30 06 Aqh0.
    main, WRITE: SSL v3.1 Change Cipher Spec, length = 21
    *** Finished, v3.1
    verify_data: { 243, 49, 247, 150, 113, 86, 182, 125, 244, 163, 245, 243 }
    [write] MD5 and SHA1 hashes: len = 16
    0000: 14 00 00 0C F3 31 F7 96 71 56 B6 7D F4 A3 F5 F3 .....1..qV......
    Plaintext before ENCRYPTION: len = 36
    0000: 14 00 00 0C F3 31 F7 96 71 56 B6 7D F4 A3 F5 F3 .....1..qV......
    0010: 1A 7C 8F D9 51 CB 6F 47 2A 7C 90 81 20 EE 97 64 ....Q.oG*... ..d
    0020: FF 47 35 CA .G5.
    main, WRITE: SSL v3.1 Handshake, length = 36
    main, SEND SSL v3.1 ALERT: warning, description = close_notify
    Plaintext before ENCRYPTION: len = 22
    0000: 01 00 F0 F4 AC 3C B2 DE 95 98 0E B4 ED B1 24 3B .....<........$;
    0010: 54 6C 8B DC F3 1F Tl....
    main, WRITE: SSL v3.1 Alert, length = 22
    java.net.SocketException: Connection aborted by peer: socket write error
         void java.net.SocketOutputStream.socketWrite(java.io.FileDescriptor, byte[], int, int)
              native code
         void java.net.SocketOutputStream.write(byte[], int, int)
              SocketOutputStream.java:96
         void com.sun.net.ssl.internal.ssl.OutputRecord.a(java.io.OutputStream)
         void com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(com.sun.net.ssl.internal.ssl.OutputRecord)
         void com.sun.net.ssl.internal.ssl.HandshakeOutStream.flush()
         void com.sun.net.ssl.internal.ssl.Handshaker.sendChangeCipherSpec(com.sun.net.ssl.internal.ssl.HandshakeMessage$Finished)
         void com.sun.net.ssl.internal.ssl.ClientHandshaker.c()
         void com.sun.net.ssl.internal.ssl.ClientHandshaker.a(com.sun.net.ssl.internal.ssl.SunJSSE_o)
         void com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(byte, int)
         void com.sun.net.ssl.internal.ssl.Handshaker.process_record(com.sun.net.ssl.internal.ssl.InputRecord)
         void com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(com.sun.net.ssl.internal.ssl.InputRecord, boolean)
         void com.sun.net.ssl.internal.ssl.SSLSocketImpl.a(com.sun.net.ssl.internal.ssl.InputRecord)
         int com.sun.net.ssl.internal.ssl.AppInputStream.read(byte[], int, int)
         int java.io.InputStream.read(byte[])
              InputStream.java:91
         int java.io.InputStreamReader.fill(char[], int, int)
              InputStreamReader.java:173
         int java.io.InputStreamReader.read(char[], int, int)
              InputStreamReader.java:249
         void java.io.BufferedReader.fill()
              BufferedReader.java:139
         java.lang.String java.io.BufferedReader.readLine(boolean)
              BufferedReader.java:299
         java.lang.String java.io.BufferedReader.readLine()
              BufferedReader.java:362
         void Teste3.main(java.lang.String[])
              Teste3.java:109
    Exception in thread main
    Debugger disconnected from local process.
    Process exited with exit code 1.
    One more thing if if make the same thing via browser (https://mymachine.mydomain.pt/pvtn?someparameter=somevalue) and works fine too (obviously i pre installed the client certificate in the browser and choose the certificate when the pop up show up)
    It seems like the handshaking fails when i send data to /pvtn...
    Regards,
    Paulo.

    I amhaving the another problem very similar, I am struggling with client authentication with IIS 5.0, and receiving the 'Remote Host closed the connection' error.
    Is there any help me in this. I truly apprecaite it
    Thanks

  • Is it possible for the client to receive constantly data over tcp without\n

    Hi
    I have a server that constantly outputs measuring data. I would like some help with the client application that receives data and directly outputs. Client application is just receiving without sending anything. I have tried
    BufferedReader stdIn = new BufferedReader(
    new InputStreamReader(System.in));
         String userInput;
         while ((userInput = stdIn.readLine()) != null) {
         out.println(userInput);
         System.out.println("echo: " + in.readLine());
    But it hangs, because there is no end of line from server, how should I proceed to constantly retrieve data from server?

    I tried with
    InputStream is = new BufferedInputStream(CLSocket.getInputStream());
    System.out.println("Connected");
    is.read();
    but my application hangs (is runing without stopp, looping forever) when it comes to is.read();
    what should I do?

  • Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

    Hi,
    I am using APEX version 4.2.1.00.08 with Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    I've developed an application, that was working fine till 3 days ago...
    At the moment, I can log into the application but when I enter my ID/PW it takes me to my 1st page but then it runs for a mint or so (trying to load charts) and then generates following error message
    No data received
    Unable to load the webpage because the server sent no data.
    Here are some suggestions:
    Reload this webpage later.
    Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
    interestingly, I haven't changed anything within the application
    I've tried it with Chrome Version 27.0.1453.116 m and IE 8.0...
    with IE 8.0, it shows I/O Error in place of my graphs and get's a pop up message that displays "Error - error unknown"
    The only thing that I can recall doing differently is logging via remote desktop connection, but I've used remote desktop in the past as well and it worked.
    Please advice

    anyone...?

  • JMS Adapter: Sending data with WebSphere MQ Client to XI

    Hi,
    I want to send data from the WebSphere MQ Client to the XI. Is this possible and what do I have to do except configuring the JMS queues in Visual admin?
    Thanks in advance
    Dominic

    hi
    xi jms adapter will read/write data frm queue.
    but u want to access the jms queues in XI WAS frm ur MQ client
    ..will hv to access it directly frm ur client
    chk this
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/604e2b64-e689-2910-64b3-ffd650f83756
    rgds
    arun

  • LG Octane without a data plan. Any way I can send a text from my Octane to my computer gmail?

    I have an LG Octane without a data plan (have an iPad for that).  I want to send texts from my Octane to my gmail.  Any way I can do that through Verizon.  I know I can use @vtext to send email to a phone number.  But can I send a text to an email?  Thanks.

    If you have a text plan just input the email address in the to field of the text and send away.  If you don't have a text plan then I think you would be charged per text.  Mary

  • Proc_getObject with nolock causes "read operation on a large object failed while sending data to the client"

    SharePoint 2013 code for the SharePoint Config database stored procedure dbo.proc_getObject has been changed from SharePoint 2010 with the difference of select with nolock.
    I am seeing numerous Error 7886, Severity-20 errors nightly:
    "A read operation on a large object failed while sending data to the client. A common cause for this is if the application is running in READ UNCOMMITTED isolation level. This connection will be terminated."
    Here I have commented out "with (nolock)" to 'fix' the error and to align the store proc with SharePoint 2010 code : 
    ALTER PROCEDURE [dbo].[proc_getObject]
    @Id uniqueidentifier,
    @RequestGuid uniqueidentifier = NULL OUTPUT
    AS
    SET NOCOUNT ON
    SELECT
    Id,
    ParentId,
    ClassId,
    Name,
    Status,
    Version,
    Properties
    FROM
    Objects --with (nolock)
    WHERE
    Id = @Id
    RETURN 0
    How is this stored procedure called and for what use?
    Why did Microsoft make this change to SharePoint 2013 - some performance gain through dirty reads at the cost of stability? Or what could be a reason for this to happen that can be fixed?

    GetObject retrieves any farm object that is selected (by ID). Changing this is obviously not supported, and NoLock was used to (help) prevent locks when performing a select query.
    I've never seen this issue, and would guess it is unique to your environment given this is such a core piece of the SharePoint infrastructure.
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Detect client disconnection

    Hi.
    My Java Web Service works with ComPorts so I need to close it in a right way when a client disconnects.
    Is there a way to detect in the Web Service when a client disconnects.
    Thank�s you all!!

    So, i want to be able to find out if the client is disconnected without waiting to send or receive data.Use a read timeout.
    how can i change the value of SO_KEEPALIVEYou can't. It is two hours by default and requires privilege to change it, and changing it is system-wide. So you don't want to do that.
    Use a read timeout. Socket.setSoTimeout().

  • Server to detect client disconnection "Sockets"

    i want to know how it is possible for a server to find out when the client is disconnected at any instance. not only at the time of sending data...
    i am writing a server that should communicate with different clients, and i want it to be able to find out if a client suddenly disconnects or crashes, so how can this be done?!
    is it this way:
    skt.setKeepAlive(true);the problem is that SO_KEEPALIVE checks after 2 hours, which is too much time, how can i change this value????

    So, i want to be able to find out if the client is disconnected without waiting to send or receive data.Use a read timeout.
    how can i change the value of SO_KEEPALIVEYou can't. It is two hours by default and requires privilege to change it, and changing it is system-wide. So you don't want to do that.
    Use a read timeout. Socket.setSoTimeout().

  • Continuously send data to applet through servlet

    Hi,
    I'm trying to write a servlet that, once activated, will continuously send data back to a thread in the client. My problem is that the data isn't actually sent until the stream is closed. I'm hoping someone can point me in the right direction:
    Servlet code:
    public class testStream extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    int[] somedata = new int [1];
    somedata [0] = 1000;
    String contentType =
    "application/x-java-serialized-object";
    response.setContentType(contentType);
    ObjectOutputStream out =
    new ObjectOutputStream(response.getOutputStream());
    while (true) {
    try {
    out.writeObject(somedata );
    System.out.println("Sent " + somedata [0]);
    somedata [0]++;
    } catch(Exception ie) {}
    out.flush();
    Thread.yield();
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    Applet side code:
    * <P>
    * Taken from Core Servlets and JavaServer Pages
    * from Prentice Hall and Sun Microsystems Press,
    * http://www.coreservlets.com/.
    * &copy; 2000 Marty Hall; may be freely used or adapted.
    public class testStream implements Runnable {
    private boolean isDone = false;
    private URL dataURL;
    public testStream(String urlSuffix, URL currentPage) {
    try {
    // Only the URL suffix need be supplied, since
    // the rest of the URL is derived from the current page.
    String protocol = currentPage.getProtocol();
    String host = currentPage.getHost();
    int port = currentPage.getPort();
    dataURL = new URL(protocol, host, port, urlSuffix);
    Thread imageRetriever = new Thread(this);
    imageRetriever.start();
    } catch(MalformedURLException mfe) {
    System.err.println("Bad URL");
    isDone = true;
    public void run() {
    try {
    retrieveImage();
    } catch(IOException ioe) {
    isDone = true; // will never get hit
    public boolean isDone() {  // meaningless now with infinite loop
    return(isDone);
    private void retrieveImage() throws IOException {
    URLConnection connection = dataURL.openConnection();
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDefaultUseCaches (false);
    connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    ObjectInputStream in = null;
    try {
    in = new ObjectInputStream(connection.getInputStream());
    } catch (Exception pe) { System.err.println(pe); }
    while (true) {
    // loop forever requesting data
    try {
    // The return type of readObject is Object, so
    // I need a typecast to the actual type.
    int[] someData = (int[]) in.readObject();
    System.err.println(someData[0]);
    } catch(ClassNotFoundException cnfe) {
    System.err.println("received NULL");
    Thread.yield();

    The original example was based on HTTP. I suppose yours is too. The HTTP protocol is for sending and receiving packets of finite length, and that is not your requirement. So don't use HTTP. Probably socket communications would be your best bet.

  • Errors in sending data - maybe a bug

    Hi, everybody. I was trying o create a program with 2 scokets, lets say socket A and socketB. The principle of this program was whatever socketA receives is beeing send through socketb and vis versa. I had creted a routine for sendind data like that:
    public int SendData(String s){
    try{         
         out.print(s); //this is a printwriter
    out.flush();
    }catch(Exception e){
    System.out.println("Error in sending data"+ e.toString());
    return -1;
    return 0;
    The strange thing was that, using a network sniffer I realised that sometimes my socket was sending characters that weren't in the string s, more precisly it was the character with hex value c2 . When I made the following modification the program worked correctly
    public int SendData(String s){
    try{         
         for(int i=0;i <s.length() ;i++)
              out.write((int)(s.charAt(i))); //now out is an OututSream and not a PrintWriter
    }catch(Exception e){
    System.out.println("Error in sending data"+ e.toString());
    return -1;
    return 0;
    Maybe can anybody explain why was this happening? I am curious to hear your opinion!
    My java -version result is:
    java version "1.5.0-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-beta-b32c)
    Java HotSpot(TM) Client VM (build 1.5.0-beta-b32c, mixed mode)

    I'm not sure what you need to do. If you want to send and receive binary data, read and write bytes (or there are other ways, e.g. DataOutputStream).
    If you want / need to send Unicode text, a PrintWriter / OutputStreamWriter and InputStreamReader will convert Unicode to & from e.g. utf-8. Or you can use String.getBytes() and new String(s, "utf-8") to convert:
    public class t
        public static void main(String args[])
            throws Exception
            String s = "ab\u00a2\03c0";
            System.out.println("string: " + s);
            byte bytes[] = s.getBytes("utf-8");
            System.out.println("bytes: " + toString(bytes));
            String decoded = new String(bytes, "utf-8");
            System.out.println("decoded: " + decoded);
        static String toString(byte b[])
            StringBuffer buf = new StringBuffer();
            for (int n = 0; n < b.length; n++) {
                if (n != 0)
                    buf.append(", ");
                buf.append(Integer.toHexString(b[n] & 0xff));
            return buf.toString();
    }I'd probably use String.getBytes() instead of PrintWriter; that allows mixing text and non-text data.
    Ok, quite possibly Unicode is overkill for you, and you'll be fine with the 8-bit subset. Depends on how "serious" your application is, and how likely it will need to process e.g. Cyrillic, Greek or Chinese text.
    For performance, you may want buffered streams and a StringBuffer instead of string concatenation to create strings.

Maybe you are looking for