Java Socket Close Detection, Late FINs

This is a wierd problem I have been facing.
I understand that the only way that you can detect a remote client socket close(graceful only, NOT reset) in java is through reading (or writing )on a socket and detect IOException. For the final FIN/ACK the server should close the socket in the Exception handling.
I have a server that currently does this in two ways. I read on the socket for a message on the socket.
1. Using a DataInputStream (reads 2Bytes)
2. Using a BufferedReader (reads a line)
I have a client that opens n connections and closes them after 20 sec. I am doing 'netstat -al' to grep on the port to determine the status of connections on the server.
Problem 1.
When I am using BufferedReader, and open 100 connections to the server and close them (after 20 sec), I see that all the connections are closed in a matter of ms. (netstat -al| grep <portnum> shows no connections in CLOSE_WAIT). But on the other hand when I use DataInputStream some connections are lingering in CLOSE_WAIT for more than 20 seconds (this time increases with the number of connections).
Why is this?
Problem 2.
The DataInputStream.read(2bytearray) does not throw IOException when I close the socket on the client side. It blocks till I close the connection on the client side. When the connection is closed the read succeeds. This to me is really wierd. Is this not a bug?
I tried DataInputStream.readFully(2bytearray) and this works. This throws an Exception when the Client socket is closed.
Any light on these issues is extremely appreciated.
Thanks
Subu

Thanks for the response. That was a good point. I tried the BufferedInputStream also. This also does not seem really fast. For 100 connections it takes about 5 - 10 seconds. But even that is high. I dont think the server is a processing bottleneck. This is a production machine I am testing with. In any case I will do a top next to see that. (If 100 connections are high for the server, both the versions of the server should perform the sameway right)
Thanks
Subu

Similar Messages

  • Connecting to http web site using java socket

    Hi,
    Sockets in Java I believe are reusable. Once created, it can be used to send a request using its input stream and get back a response using the output stream. My problem is I am trying to connect to a website using java socket but I am unable to get a response (though the same works fine I use URL and URLConnection). Can anyone tell me whats wrong? Below is the client program:
    public class HttpAdapterTest {
         public static void main(String[] args) {
              try {
                   Socket socket = new Socket("www.google.com", 80);
                   BufferedWriter out = new BufferedWriter(
                                  new OutputStreamWriter(socket.getOutputStream()));
                   out.write("GET /help/basics.html HTTP/1.1");
                   out.flush();
                   BufferedReader in = new BufferedReader(
                                            new InputStreamReader(ucon.getInputStream()));
                   String line = null;
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                   in.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Look at the JSSE examples. You need to setup a key store, add the jsse jars to your classpath, yadda, yadda, yadda....

  • Using plain Java Sockets(not RMI) how..?

    hi!
    1. Using plain Java Sockets(not RMI) how can the client detect when its server
    goes down?
    There is a long time interval between client requests and the client wants
    to retain a live connection rather than disconnect after every reqest.
    Please also cc your reply to [email protected]
    Thanks,
    \Raghu

    If you try to send data when the host is gone, it throws an exception. I don'thow to check if it is alive though. I'm having the same problem right now.

  • Java socket - unsure road to take!

    Hi all,
    We have an application requiring data transfer from a JSP Web application (socket client) and a stand-alone java application (socket server).
    This java stand-alone app communicates to an industrial microcontroller connected to the RS-232 serial port.
    When this java apps received a command from the JSP web app, it cannot service any other command from other uses, since there is just one RS-232 serial port on the computer. We would like to rely on the java & network environment to buffer additional commands receive simultaneously, as opposed to write code on the java socket server to handle this. In other works, our java stand-alone operates in an assynchronous, single-task mode.
    We are unsure which approach to take as far as java socket goes:
    1) simple socket server/client;
    2) multithread socket
    3) pooled
    Can anyone advise us.
    Thank you
    Trajano

    Hi Pete,
    1) Yes, we can have more than one user trying to access the micro-controllers, because we have in reality a network of micro-controllers connected to the single RS-232 computer port via a RS-485 to RS-232 converter;
    2) If a second user tries to issue a command to micro-controller, I would prefer for the java socket/environment to take care of the buffering, by just delaying the response, until the first user gets its command serviced
    3) If there is 1 user, him/her might issue several commands at the same time, by opening several JSP pages;
    4) No the controllers can service any instruction coming up at any time. The protocol is master/slave. The java app issues a request and the micro-controlle replies back and ready to accept any other request.
    ISSUE: My preference is for the system to take care of commands arriving at the socket server.
    This java app has two threads:
    1) Thread1 is the java socket server and upon receiving a command it will update three (3) properties:
    micro-controller address, command and product code
    2) Thread32 will be responsible for polling the 3 properties to check if they've changed. Upon detecting a change, it will build the data string and send to the RS-232 serial port.
    Any ideas/suggestions.
    Thanks in advance for any assistance.
    Regards

  • Socket AS3 ( Receive File .TXT ) + Java Socket

    Hi,
    I have Java Socket sending .TXT file ( 10 MB ) . But the AS3 only gets 63 Kb . I do not understand the loss of bytes ...
    Souce Java :
    public void sendFile(String fileName) {
            try {
                //handle file read
                File myFile = new File(fileName);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                dis.readFully(mybytearray, 0, mybytearray.length);
                OutputStream os = clientSocket.getOutputStream();
                byte[] fileSize = intToByte(mybytearray.length);
                byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
                System.arraycopy(fileSize, 0, clientData, 0, fileSize.length); // Copy to the file size byte array to the sending array (clientData) beginning the in the 0 index
                System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length); // Copy to the file data byte array to the sending array (clientData) beginning the in the 4 index
                DataOutputStream dos = new DataOutputStream(os);
                //dos.writeUTF(myFile.getName());
                //dos.writeInt(mybytearray.length);
                dos.write(clientData, 0, clientData.length);
                dos.flush();
    AS3 Source..
    private function onResponse(e:ProgressEvent):void {
      var file:File;
      var fs:FileStream;
      var fileData:ByteArray = new ByteArray();
      file = File.documentsDirectory.resolvePath("tmpReceive.txt");
      fs = new FileStream();
      fs.addEventListener(Event.CLOSE,onCloseFileReceive);
    if(_socket.bytesAvailable > 0) {
      while(_socket.bytesAvailable) {
      // read the socket data into the fileData
      _socket.readBytes(fileData,0,0);
      fs.open(file, FileMode.WRITE);
      // Writing the file
      fs.writeBytes(fileData);
      fs.close();

    Crypto streams, like CipherInputStream andCipherOutputStream, do not behave properly until you
    issue a close() call. So if you are going to do
    crypto, you will need to trap the close() before it
    reaches the underlying socket streams. This is
    because the close() method finalizes the cryptographic
    operation. (Flush() would make more sense, no idea
    why they did it this way). You do want to finalize
    the crypto for any given message, but you need to trap
    the close() before it hits the socket and ends the
    whole affair.
    I don't see anything about that in the bug database.
    No matter what streams you are using, if you aregoing to keep the socket open for multiple
    request-response round-trips, you need to very closely
    pay attention to how much data is being sent on each
    trip. Normally, you can fudge this a bit on a
    request-response because the close() call on the
    output stream will cause the receiving input stream to
    behave more or less properly. However, a flush() will
    not.Why not? I use that all the time with no problem.
    A good practice is to send the content-length of
    the message first, so the receiving input stream
    "knows" when to stop reading, does not block, and then
    can send its own bytes back the other direction.
    (Where the process is repeated).
    An alternative is to use two threads: read and write.
    The read recieves, parses, validates and then pushes complete messages to a queue.
    The write pulls messages from the queue, processes and send a result.
    A variation to the above is what happens when an invalid message is received. The server can ignore it, the read can send a error response, or the read can push a message to the queue which causes the write to send a error response.

  • Socket.close() on both sides?

    Hello
    i'm creating a server-client application, but i came at a problem:
    i currently testing the logging out or disconnection.
    The protocol does this: client sends packet to server with request for logout, server pushes response back and ?closes socket?, client reads response and ?closes socket?
    now this is where i don't understand what i should do... should i close the socket on server side, or at client side ?
    the thing is after the server received that packet, it sends packet back for confirmation and then unregisters the client, this means removing it from the client list (where it holds all clients for updating purposes at server side etc) and it closes its read/write thread, so stopping the thread from running. but should i also close the socket then?
    or should i let the client close the socket? because while i send my packet of logout and receiving it, im also pinging (sending empty packet) the server to make sure the server is still online and server writes response back (this is a default operation, every 600ms), and when i close the socket on server side this will give offcourse an exception at clientside before i received the packet, so what should i do ??
    Thanks in advnace!

    You seem to have obfuscated what you actually want help with quite well,
    this is my guess.
    796870 wrote:
    ... or should i let the client close the socket?
    because while i send my packet of logout and receiving it, im also pinging (sending empty packet) the server to make sure the server is still online and server writes response back (this is a default operation, every 600ms), and
    when i close the socket on server side this will give offcourse an exception at client sideYour [url http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination]connection termination (wiki) results in RST.
    before i received the packet, so what should i do ?For both server and client, when you are done sending data you use [url http://download.oracle.com/javase/6/docs/api/java/net/Socket.html#shutdownOutput%28%29]Socket.shutdownOutput() (javadoc).
    EOS will result when the other party attempts to read() beyond the data available.
    The other party can finish writing and use [url http://download.oracle.com/javase/6/docs/api/java/net/Socket.html#close%28%29]Socket.close() (javadoc) and
    EOS will result when the first party attempts to read() beyond the data available.
    The first party can then use [url http://download.oracle.com/javase/6/docs/api/java/net/Socket.html#close%28%29]Socket.close() (javadoc) which completes [url http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination]connection termination (wiki).

  • Java sockets (peek functionality)

    Hi,
    how do i peek at a datagram, look into the data and accordingly
    decide whether to consume that datagram or leave it for later
    processing?
    Is this something Java sockets readily support OR do I need
    to implement some kind of store-for-later-processing
    please help
    Thanks.

    java.net.DatagramSocket doesn't have peek support in the API at this time - see 4102648.
    If you were to use a non-blocking DatagramChannel and register it with a Selector then you should be notification that a packet can be read. Okay, it doesn't give you the details - just that a packet is available but it may help in your environment.

  • Java socket not handling the data packets properly

    I have created a small webserver application where i am receiving http requests from a siebel client. I am using content-length parameter to read the complete data in a buffer string using the command inputstreamreader.read. It works fine in all the cases, except when its used with a firewall. Some times the firewall splits a message into 2 and my logic fails as it doesn't find as many characters in the first packet as mentioned in the content length.
    My question is , how can i take care of these scenarios where a firewall is splitting the messages into multiple packets. why the java socket class is not handling the merging of these packets?
    any pointers are welcome.
    thanks

    Because that's the way TCP/IP works. read() gives you the data it can, and tells you how much was actually read. It's up to the application to reconstruct the application-level object. You could do something like this:    byte[] content = new byte[contentLen];
        int offset = 0;
        int remaining = contentLen;
        int currBytesRead = 0;
        while (remaining > 0 && currBytesRead != -1) {
          int currBytesRead = mySocketInputStream.read(content, offset, remaining);
          remaining -= currBytesRead;
          offset += currBytesRead;
        } (Warning: that's off the top of my head, uncompiled and untested. Use for demonstration purposes only!)
    Grant

  • Problem while reading data on java socket

    Hi All,
    I am in big problem based on java socket programming. I run my application and start a ServerSocket on 10000(suppose) port no.As soon as request is coming i create a new thread with Socket assigned to it and process the request. Now i got the response and written on same Socket(Listen to ServerSocket on 10000 port). Now what i want to read the response written earlier on Socket.The written response i print on SOP it is visible. But when i establish InputStream and try to read the data it gives me -1 means no data is available. But i have seen the SOP and data is written to socket. How can solve the problem. I have tried after close the Socket as well as not close the socket.
    Please help me out on this.see below code
    <CODE>
    void upperClassMethod() {
    istener = new ServerSocket(port);
    while(true) {
    clientSocket = listener.accept();
    doComms conn_c= new doComms(clientSocket);
    Thread t = new Thread(conn_c);
    t.start();
    //doComms is a inner class of upper level class
    class doComms implements Runnable {
              private Socket server;
              doComms(Socket server) {
                   //pp = server;
                   this.server=server;
                   //server=server1;
    void processResponse() {
              try {
                   BufferedInputStream in = new BufferedInputStream (clientSocket.getInputStream());
                   byte [] inBuff = new byte [4096] ;
                   int len = in.read (inBuff, 0, inBuff.length) ;
                   String output = new String (inBuff) ;
                   System.out.println("the output is :::: "+output);
              } catch(Exception e) {
                   e.printStackTrace();
    </CODE>
    in processResponse() method i am not able to get output. Plz help me guys.....
    Thanks in advance for ant assistance
    Regards,
    Pradeep

    please see mu rum nethos of doComms class
    <CODE>
    public void run () {
                   input="";
                   boolean done = false ;
                   try {
                        BufferedInputStream in = new BufferedInputStream (server.getInputStream());
                        out = new PrintStream(server.getOutputStream());
                        while (!done) {
                             byte [] inBuff = new byte [4096] ;
                             try {
                                  int len = in.read (inBuff, 0, inBuff.length) ;
                                  if (len > 0) {
                                       input = new String (inBuff) ;
                                       Runnable r = new RequestProcessThread();
                                       Thread t = new Thread(r);
                                       t.start();
                                  } else if (len == -1) {
                                       done = true ;
                                       //server.close () ;
                             catch (InterruptedIOException iioe) {
                   } catch (IOException ioe) {
                        System.out.println("IOException " + ioe + " on socket in thread: " + Thread.currentThread().getName());
                        ioe.printStackTrace();
                        done = true ;
    </CODE>

  • Java socket run on localhost against outside server

    Hi everyone,
    I am newbie to Java socket and networking. By spending this weekend over the internet reading and researching I have made my first Server-Client java socket program run sucessfully on my localhost 127.0.0.1. They can be connected and ok to communicate.
    However, when I put my server program to the LIVE server outside the network the client side says cannot connect to the server because: Connection Error, Connection refused: connect. So I read some stuff about firewall and NAT on the web but i was shamed that I don't understand there is any solution to this.
    It is great appreciated if someone can point me out how can I resolve this or make a step out because I am running out of time to give out the program against the deadline. But I really thank you anyone has been reading this.
    The server code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package instantmessenger;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
        public class Server extends JFrame implements ActionListener {
            JTextArea textreceive   =new JTextArea();
            JTextArea textsend      =new JTextArea();
            JButton button          =new JButton("Send");
            BufferedReader in;
            PrintWriter out;
            public Server () {
                    //init   controls
                    setTitle("Server");
                    setBounds(50,50,500,400);
                    getContentPane().setLayout(null);
                    getContentPane().add(textreceive);
                    getContentPane().add(textsend);
                    getContentPane().add(button);
                    textreceive.setBounds(10,10,450,300);
                    textsend.setBounds(10,320,350,30);
                    button.setBounds(370,320,70,30);
                    button.addActionListener(this);
            public void listenClient() throws IOException {
                    ServerSocket   server=new   ServerSocket(9999);
                    System.out.println("start:"+server);
                    textreceive.append("start"+server+"\n");
                    try {
                            Socket s = server.accept();
                            try {
                                    System.out.println("connecting   :"+s);
                                    textreceive.append("connecting   :"+s+"\n");
                                    in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                                        out=new   PrintWriter(
                                        new   BufferedWriter(
                                        new   OutputStreamWriter(s.getOutputStream())));
                                    out = new PrintWriter(s.getOutputStream());
                                    String str=null;
                                    while(true) {
                                            str = in.readLine();
                                            System.out.println(str);
                                            textreceive.append(str+"\n");
                            finally {
                                s.close();
                    finally {
                        server.close();
            } // end function
            public void actionPerformed(ActionEvent event) {
                    String str = textsend.getText();
                    if( !str.equals("")) {
                            out.println(textsend.getText());
                            //out.println(textsend.getText());
                            out.flush();
                            textreceive.append(textsend.getText()+"\n");
                            textsend.setText("");
            } // end function
            public   static   void   main(String   args[])   throws   IOException {
                Server   s=new   Server();
                s.show();
                s.listenClient();
            } // end function
        } // end classThe client source code:
    package instantmessenger;
        import   java.net.*;
        import   java.io.*;
        import   javax.swing.*;
        import   java.awt.*;
        import   java.awt.event.*;
        public   class   Client   extends   JFrame implements   ActionListener {
            JTextArea   textreceive=new   JTextArea();
            JTextArea   textsend   =new   JTextArea();
            JButton     button   =new   JButton   ("Send");
            BufferedReader  in;
            PrintWriter     out;
            public Client(){
                    //init   controls
                    setTitle("Client");
                    setBounds(50,50,500,400);
                    getContentPane().setLayout(null);
                    getContentPane().add(textreceive);
                    getContentPane().add(textsend);
                    getContentPane().add(button);
                    button.addActionListener(this);
                    textreceive.setBounds(10,10,450,300);
                    textsend.setBounds(10,320,350,30);
                    button.setBounds(370,320,70,30);
           } // init
            public void startNet() throws IOException {
                  //Socket client=new Socket("localhost",9999);
                  Socket client=new Socket("222.33.444.5555",9999);  // NOT REAL SERVER IP
                  try {
                          System.out.println("Socket="   +client);
                          in    =   new BufferedReader(new InputStreamReader(client.getInputStream()));
                          out   =   new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
                          String str=null;
                          while(true) {
                              str   =   in.readLine();
                              System.out.println(str);
                              textreceive.append(str+"\n");
                  finally {
                        client.close();
            } // end function
            public void actionPerformed(ActionEvent   event) {
                String str=textsend.getText();
                if(!str.equals("")) {
                    out.println(textsend.getText());
                    //out.println(textsend.getText());
                    out.flush();
                    textreceive.append(textsend.getText()+"\n");
                    textsend.setText("");
            } // function
            public static void main(String args[]) throws IOException {
                Client c=new Client();
                c.show();
                c.startNet();
            } // function
    } // end classThank you
    Morris Lee

    However, when I put my server program to the LIVE server outside the network the client side says cannot connect to the server because: Connection Error, Connection refused: connect. So I read some stuff about firewall and NAT on the web but i was shamed that I don't understand there is any solution to this.What do you want us to do? You already know that the problem probably is that you need to open port 9999 in the firewall, and you probably also need to configure it for port forwarding.
    Most clients will be able to connect after that, but some might still have problems. E.g. some companies don't allow clients to connect to other ports than a few well known ones (e.g. 21, 80 and 443)

  • Java sockets and winsock

    when I use java socket to talk to my proxy, without going through a winsock, my java applet runs fine. However, when I patch winsock in between my java gui and my other proxy, I dont receive anything in the gui. I snoop at packets coming from my other proxy through winsock to my gui and the data is all there. I just cannot receive it.
    I use java class DatagramSocket() to establish a socket connection and use class DatagramPacket to get the packets coming. This works if I dont go through a ms proxy.
    Can anyone tell me why?

    How can you snoop at packets comming? I need to know so bad. :-)
    Thank you

  • Socket.close doesn't work in Windows browsers?

    I've been trying to figure this out for days and I can't seem to find anything on why this is happening or how to fix it.
    I have an FTP program written that uploads ByteArrays through sockets.  It works great on my Mac!  I open a command connection, then a data connection, send the ByteArray and then use socket.close() on my data connection.  This causes the server to disconnect me and sends the 226:transfer succeeded message back through my command connection.
    The problem is that in IE8, FF 3.5, and Safari 4 on Windows the socket.close() func does not make the server close the connection.  The fact that it works in all of my Mac browsers, and the IDE, but not in Windows browsers makes me think that it's something to do with the Flash Player.  Is this possible?
    My FP version check data:
    MAC 10,0,32,18
    WIN 10,0,32,18
    Does anyone know how I can fix, or even debug, this?

    does anyone have any idea what could be going on here?  am i completely out to lunch?

  • Since updating to Firefox 3.6.15, I can no longer print coupons from SmartSource. The error message is that Java is not detected. The check box is longer showing in the Options/Content of this version of Firefox, so I can not enable it.

    # Question
    Since updating to Firefox 3.6.15, I can no longer print coupons from SmartSource. The error message is that Java is not detected. The check box is longer showing in the Options/Content of this version of Firefox, so I can not enable it.

    Same PC as I used to post the question. When I go to the "plug in check" page, it shows I am up to date and it is not disabled.
    Java(TM) Platform SE 6 U24
    Next Generation Java Plug-in 1.6.0_24 for Mozilla browsers 1.6.0.24

  • Why won't my Mac detect my iPhone which was just upgraded to iOS 6.1.  My other phone still at 6.0.1 is detected just fine.

    Why won't my Mac detect my iPhone 4 which was just upgraded to iOS 6.1.  My other iPhone 4 is still at 6.0.1 and is detected just fine.  Is anyone else having this problem?  Everything was working ok before the upgrade and still works except for the detection.  Coincidence?

    After 4 updates to Xcode it started to connect again.  Now it's working fine.

  • Java socket streams messing up

    iv wrote a games server and it uses java socket streams to send the messages back and forth between the game clients and the game server it self
    this all works great but when running and over about 5min its send over 1000 packets BUT
    it will crash iv found the reason is down to when reading the packets my parser is reading wrong part and grabbing a String part when it should be a INT
    now it should NEVER be reading this part of the packet so i put a trace on the packets coming in and ran it every packet was been read in perfect THEN just befor the crash TWO packets were merged together stright out from the socket stream this is y my packet reader was getting confused
    what im asking is can this happen in java sockets ? i thought they were bufferered so no matter how fast you send data it would always read it out in the same order ?? not sure how its merging these to packets
    is this possible of is my reader got an error in it altho works 95% of the time ??

    or do you have multiple buffered streams created from the same socket?

Maybe you are looking for