StreamReader from TCP Socket Hanging...I think

Hello all, and thank you in advance for any and all help. Allow me to start out by apologizing as I have only been programming Java for about 3 days now, however I am a bit stuck and have spent about 5 hours trying to figure out what could be my problem here.
I have written an app that connects to a usenet server and pulls that list of groups from the server, however it seems as if the BufferedReader doesn't have a large enough buffer to hold the response from ther server. I can save the output of the log from putty during the LIST command and I recieve 108897 lines of text (about 5 mb in total) however in my Java app it gets to line #108598 and hangs. I have tried messing with the buffer sizes of the StreamReader as well as the Socket, and if I try to set the buffer size of the BufferedReader {+bufferedreader(stream,int)}+ It won't compile.
Well here is the code, and again, i apologize if this is sloppy/not correct coding practices. I am new at Java.
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    try {
        String data = "";
        Socket skt = new Socket("127.0.0.1", 119);
        BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
        while (!in.ready()){}
        data = in.readLine();
        //log.append(data.toString() + "\n");
        Scanner sc = new Scanner(data);
        int command = sc.nextInt();
        if (command == 200) {
            log.append("Connection established to" + sc.nextLine() + "\n");
            log.append("Sending Log-in Credentials \n");
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            out.println("AUTHINFO USER " + txtUser.getText());
            while (!in.ready()){}
            data = in.readLine();
            sc = new Scanner(data);
            command = sc.nextInt();
            if (command == 381) {
                out.println("AUTHINFO PASS " + txtPass.getText());
            while (!in.ready()){}
            data = in.readLine();
            sc = new Scanner(data);
            command = sc.nextInt();
            if (command == 281) {
                log.append("Successfully logged in \n");
                log.append("Getting list of active groups \n");
                out.println("list");
                while (!in.ready()){}
                data=in.readLine();
                Writer output = null;
                File outfile = new File("c:/data/groups.txt");
                output = new BufferedWriter(new FileWriter(outfile));
                output.write(data + "\n");
                out.println("Date");
                int i = 0;
                while ( i != 108897) {
                    data = in.readLine();
                    output.write(data + "\n");
                    i += 1;
    catch (Exception ex) {
        System.out.print(ex.getMessage());

while (!in.ready()){}Remove that. It's just burning CPU. The following readLine() will block until the line arrives.
while (!in.ready()){}Ditto.
while (!in.ready()){}Ditto.
while (!in.ready()){}Ditto.
while ( i != 108897) {
data = in.readLine();At this point (and every other readLine()) you must check for data == null, which is EOS, and break, and close the stream, if you get it.

Similar Messages

  • Reading text from server socket stream

    I have a basic cd input program i've been trying to figure out the following problem for a while now, the user enters the artist and title etc and then a DOM (XML) file is created in memory this is then sent to the server. The server then echos back the results which is later printed on a html page by reading the replys from the server line by line.
    The server must be run it listens for clients connecting the clients connect and send DOM documents through the following jsp code.
    <%@page import="java.io.*"%>
    <%@page import="java.net.*"%>
    <%@page import="javax.xml.parsers.*"%>
    <%@page import="org.w3c.dom.*"%>
    <%@page import="org.apache.xml.serialize.*"%>
    <%!
       public static final String serverHost = "cdserver";
       public static final int serverPort = 10151;
    %>
    <hr />
    <pre>
    <%
            Socket mySocket = null;          // socket object
            PrintWriter sockOut = null;      // to send data to the socket
            BufferedReader sockIn = null;    // to receive data from the socket
            try {
                //  #1 add line that creates a client socket
                mySocket = new Socket(serverHost, serverPort);
                // #2 add lines that create input and output streams
                //            attached to the socket you just created
                 sockOut = new PrintWriter(mySocket.getOutputStream(), true);
                 sockIn = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            } catch (UnknownHostException e) {
                throw e; // This time the JSP can handle the exception, not us
            } catch (IOException e) {
                throw e; // This time the JSP can handle the exception, not us
    String cdTitle, cdArtist, track1Title, track1Time, track1Rating;
    // Retrieve the HTML form field values
    cdTitle = request.getParameter("cdtitle");
    cdArtist = request.getParameter("cdartist");
    track1Title = request.getParameter("track1title");
    track1Time = request.getParameter("track1time");
    track1Rating = request.getParameter("track1rating");
    // Create a new DOM factory, and from that a new DOM builder object
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Note that we are creating a new (empty) document
    Document document = builder.newDocument();
    // The root element of our document wil be <cd>
    // It gets stored as the child node of the whole document (it is the root)
    Element rootElement = document.createElement("cd");
    document.appendChild(rootElement);
    // Create an element for the CD title called <title>
    Element cdTitleElement = document.createElement("title");
    // Add a text code under the <title> element with the value that
    // the user entered into the title field of the web form (cdTitle)
    cdTitleElement.appendChild(document.createTextNode(cdTitle));
    // Place the <title> element underneath the <cd> element in the tree
    rootElement.appendChild(cdTitleElement);
    // Create an <artist> element with the form data, place underneath <cd>
    Element cdArtistElement = document.createElement("artist");
    cdArtistElement.appendChild(document.createTextNode(cdArtist));
    rootElement.appendChild(cdArtistElement);
    // Create a <tracklist> element and place it underneath <cd> in the tree
    // Note that it has no text node associated with it (it not a leaf node)
    Element trackListElement = document.createElement("tracklist");
    rootElement.appendChild(trackListElement);
    // In this example we only have one track, so it is not necessary to
    // use a loop (in fact it is quite silly)
    // But the code below is included to demonstrate how you could loop
    // through and add a set of different tracks one by one if you
    // needed to (although you would need to have the track data already
    // stored in an array or a java.util.Vector or similar
    int numTracks = 1;
    for (int i=0; i<numTracks; i++) {
      String trackNum = Integer.toString(i+1);
      Element trackElement = document.createElement("track");
      trackElement.setAttribute("id", trackNum);
      trackListElement.appendChild(trackElement);
      // Track title element called <title>, placed underneath <track>
      Element trackTitleElement = document.createElement("title");
      trackTitleElement.appendChild(document.createTextNode(track1Title));
      trackElement.appendChild(trackTitleElement);
      // Track time element called <time>, placed underneath <track>
      Element trackTimeElement = document.createElement("time");
      trackTimeElement.appendChild(document.createTextNode(track1Time));
      trackElement.appendChild(trackTimeElement);
      // Track rating element called <rating>, placed underneath <track>
      Element trackRatingElement = document.createElement("rating");
      trackRatingElement.appendChild(document.createTextNode(track1Rating));
      trackElement.appendChild(trackRatingElement);
    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    // Create a new XMLSerializer that will be used to write out the XML
    // This time we will serialize it to the socket
    // #3 change this line so that it serializes to the socket,
    // not to the "out" object
    XMLSerializer serializer = new XMLSerializer(writer, format);
    serializer.serialize(document);
            // Print out a message to indicate the end of the data, and
            // flush the stream so all the data gets sent now
            sockOut.println("<!--QUIT-->");
            sockOut.flush();
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
             #4 add a while loop that reads text from the
            server socket input stream, line by line, and prints
            it out to the web page, using out.println(...);
            Note that because the reply from the server will contain
            XML, you will need to call upon the toHTMLString() method
            defined below to escape the < and > symbols so that they
            will display correctly in the web browser.
            Also note that as you receive the reply back from the
            server, you should look out for the special <!--QUIT-->
            string that will indicate when there is no more data
            to receive.
            while ((fromServer = sockIn.readLine()) != null) {
            out.println(sockIn.readLine());
                // If the reply from the server said "QUIT", exit from the
                // while loop by using a break statement.
                if (fromServer.equals("QUIT")) {
                    out.println("Connection closed - good bye ...");
                // Print the text from the server out to the user's screen
                out.println("Reply from Server: " + fromServer);
                // Now read a line of text from the keyboard (typed by user)
                fromUser = stdIn.readLine();
                // If it wasn't null, print it out to the screen, and also
                // print a copy of it out to the socket
                if (fromUser != null) {
                    out.println("Client: " + fromUser);
                    sockOut.println(fromUser);
            // Close all the streams we have open, and then close the socket
            sockOut.close();
            sockIn.close();
            mySocket.close();
    %>
    I'm suppose to modify the commented sections labled with #.
    #1,2 are correct but i have doubts on the 3rd and 4th modification.
    for #3 i changed so i serializes to the socket not to the "out" object:
    from
    XMLSerializer serializer = new XMLSerializer(out, format);
    to
    XMLSerializer serializer = new XMLSerializer(writer, format);
    with "out" it prints out some of the results entered but it just hangs i'm thinking it might be the while loop that i added in #4. If i changed it to serialize the socket XMLSerializer serializer = new XMLSerializer(writer, format); it doesn't print out nothing at all; just a blank screen where it hangs.
    I can post the rest of the code (server thats in java and cdinput.html) but since i want to keep my post short and if required i'll post it later on i also omitted some of the code where it creates the DOM textnodes etc to keep my post short.

    On your previous thread, why did you say the server was using http POST and application/xml content type when it quite obviously isn't, but a direct socket communication that abuses XML comments for message end delimiters?
    The comments imply you need to wait for "<!--QUIT-->" on a line by itself, but your loop is waiting for "QUIT".
    Pete

  • Having issues finding out how many bytes are sent/recieved from a socket.

    Hello everyone.
    I've searched the forums and also google and it seems I can't find a way to figure out how many bytes are sent from a socket and then how many bytes are read in from a socket.
    My server program accepts a string (an event) and I parse that string up, gathering the relevant information and I need to send it to another server for more processing.
    Inside my server program after receiving the data ( a string) I then open another port and send it off to the other server. But I would like to know how many bytes I send from my server to the other server via the client socket.
    So at the end of the connection I can compare the lengths to make sure, I sent as many bytes as the server on the other end received.
    Here's my run() function in my server program (my server is multi threaded, so on each new client connection it spawns a new thread and does the following):
    NOTE: this line is where it sends the string to the other server:
    //sending the string version of the message object to the
                        //output server
                        out.println(msg.toString());
    //SERVER
    public class MultiThreadServer implements Runnable {
         Socket csocket;
         MultiThreadServer(Socket csocket) {
              this.csocket = csocket;
         public void run() {
              //setting up sockets
              Socket outputServ = null;
              //create a message database to store events
              MessageDB testDB = new MessageDB();
              try {
                   //setting up channel to recieve events from the omnibus server
                   BufferedReader in = new BufferedReader(new InputStreamReader(
                             csocket.getInputStream()));
                   //This socket will be used to send events to the z/OS reciever
                   //we will need a new socket each time because this is a multi-threaded
                   //server thus, the  z/OS reciever (outputServ) will need to be
                   //multi threaded to handle all the output.
                   outputServ = new Socket("localhost", 1234);
                   //Setting up channel to send data to outputserv
                   PrintWriter out = new PrintWriter(new OutputStreamWriter(outputServ
                             .getOutputStream()));
                   String input;
                   //accepting events from omnibus server and storing them
                   //in a string for later processing.
                   while ((input = in.readLine()) != null) {
                        //accepting and printing out events from omnibus server
                        //also printing out connected client information
                        System.out.println("Event from: "
                                  + csocket.getInetAddress().getHostName() + "-> "
                                  + input + "\n");
                        System.out.println("Waiting for data...");
                        //---------putting string into a message object-------------///
                        // creating a scanner to parse
                        Scanner scanner = new Scanner(input);
                        Scanner scannerPop = new Scanner(input);
                        //Creating a new message to hold information
                        Message msg = new Message();                    
                        //place Scanner object here:
                        MessageParser.printTokens(scanner);
                        MessageParser.populateMessage(scannerPop, msg, input);
                        //calculating the length of the message once its populated with data
                        int length = msg.toString().length();
                        msg.SizeOfPacket = length;
                        //Printing test message
                        System.out.println("-------PRINTING MESSAGE BEFORE INSERT IN DB------\n");
                        System.out.println(msg.toString());
                        System.out.println("----------END PRINT----------\n");
                        //adding message to database
                        testDB.add(msg);
                        System.out.println("-------Accessing data from Map----\n");
                        testDB.print();
                        //---------------End of putting string into a message object----//
                        //sending the string version of the message object to the
                        //output server
                        out.println(msg.toString());
                        System.out.println("Waiting for data...");
                        out.flush();
                   //cleaning up
                   System.out.println("Connection closed by client.");
                   in.close();
                   out.close();
                   outputServ.close();
                   csocket.close();
              catch (SocketException e) {
                   System.err.println("Socket error: " + e);
              catch (UnknownHostException e) {
                   System.out.println("Unknown host: " + e);
              } catch (IOException e) {
                   System.out.println("IOException: " + e);
    }Heres the other server that is accepting the string:
    public class MultiThreadServer implements Runnable {
         Socket csocket;
         MultiThreadServer(Socket csocket) {
              this.csocket = csocket;
         public void run() {
              try {
                   //setting up channel to recieve events from the parser server
                   BufferedReader in = new BufferedReader(new InputStreamReader(
                             csocket.getInputStream()));
                   String input;
                   while ((input = in.readLine()) != null) {
                        //accepting and printing out events from omnibus server
                        //also printing out connected client information
                        System.out.println("Event from: "
                                  + csocket.getInetAddress().getHostName() + "-> "
                                  + input + "\n");
    System.out.println("Lenght of the string was: " + input.length());
                        System.out.println("Waiting for data...");
                   //cleaning up
                   System.out.println("Connection closed by client.");
                   in.close();
                   csocket.close();
              } catch (IOException e) {
                   System.out.println(e);
                   e.printStackTrace();
    }Here's an example of the program works right now:
    Someone sends me a string such as this:
    Enter port to run server on:
    5656
    Listening on : ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=5656]
    Waiting for client connection...
    Socket[addr=/127.0.0.1,port=4919,localport=5656] connected.
    hostname: localhost
    Ip address: 127.0.0.1:5656
    Waiting for data...
    Event from: localhost-> UPDATE: "@busch2.raleigh.ibm.com->NmosPingFail1",424,"9.27.132.139","","Omnibus","Precision Monitor Probe","Precision Monitor","@busch2.raleigh.ibm.com->NmosPingFail",5,"Ping fail for 9.27.132.139: ICMP reply timed out",07/05/07 12:29:12,07/03/07 18:02:31,07/05/07 12:29:09,07/05/07 12:29:09,0,1,194,8000,0,"",65534,0,0,0,"NmosPingFail",0,0,0,"","",0,0,"",0,"0",120,1,"9.27.132.139","","","","dyn9027132107.raleigh.ibm.com","","","",0,0,"","","NCOMS",424,""
    Now my program makes it all nice and filters out the junk and resends the new string to the other server running here:
    Enter port to run server on:
    1234
    Listening on : ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=1234]
    Waiting for client connection...
    Socket[addr=/127.0.0.1,port=4920,localport=1234] connected.
    Parser client connected.
    hostname: localhost
    Ip address: 127.0.0.1:1234
    Event from: localhost-> PacketType: UPDATE , SizeOfPacket: 577 , PacketID: 1, Identifer: UPDATE: "@busch2.raleigh.ibm.com->NmosPingFail1" , Serial: 424 , Node: "9.27.132.139" , NodeAlias: "" , Manager: "Omnibus" , Agent: "Precision Monitor Probe" , AlertGroup: "Precision Monitor" , AlertKey: "@busch2.raleigh.ibm.com->NmosPingFail" , Severity: 5 , Summary: "Ping fail for 9.27.132.139: ICMP reply timed out",StateChange: 07/05/07 12:29:12 , FirstOccurance: 07/03/07 18:02:31 , LastOccurance: 07/05/07 12:29:09 , InternalLast: 07/05/07 12:29:09 , EventId: "NmosPingFail" , LocalNodeAlias: "9.27.132.139"
    Lenght of the string was: 579
    The length of the final string I sent is 577 by using the string.length() function, but when I re-read the length after the send 2 more bytes got added, and now the length is 579.
    I tested it for several cases and in all cases its adding 2 extra bytes.
    Anyways, I think this is a bad solution to my problem but is the only one I could think of.
    Any help would be great!

    (a) You are counting characters, not bytes, and you aren't counting the line terminators that are appended by println() and removed by readLine().
    (b) You don't need to do any of this. TCP doesn't lose data. If the receiver manages get as far as reading the line terminator when reading a line, the line will be complete. Otherwise it will get an exception.
    (c) You are assuming that the original input and the result of message.toString() after constructing a Message from 'input' are the same but there is no evidence to this effect in the code you've posted. Clearly this assumption is what is at fault.
    (d) If you really want to count bytes, write yourself a FilterInputStream and a FilterOutputStream and wrap them around the socket streams before decorating them with the readers you are using. Have these classes count the bytes going past.
    (e) Don't use PrintWriter or PrintStream on socket streams unless you like exceptions being ignored. Judging by your desire to count characters, you shouldn't like this at all. Use BufferedWriter's methods to write strings and line terminators.

  • Problem reading all data from Synchronous Socket

    Hi,
    I have the task to implements an C# application which communicates with a SAP system via HTTP. My application should act as a HTTP Server to the SAP system. SAP sends documents (PDFs, Word-Docs, Tifs) through HTTP-Requests to my Server. Archive Link is SAP´s name for that HTTP interface.
    Currently I am using synchronous sockets to process the communication. So
    basically I do something like this:
            Thread th = new Thread(new ThreadStart(StartListenThreaded));
         th.Start();
    The method StartListenThread looks like this:
         private void StartListenThreaded()
                   IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                   IPEndPoint EndPoint = new IPEndPoint(ipAddress, port);
                   Socket ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                   ss.Bind( EndPoint);
                   ss.Listen(20);
                   try
                        while(true)
                             Console.WriteLine("rnServer is waiting for a new connection..rn");
                             Socket sock = ss.Accept();
                             Console.WriteLine("Accepted connection form:"+sock.RemoteEndPoint);
                             Connection con = new Connection(sock);
                             Thread t = new Thread(new ThreadStart(con.ProcessOneRequest));
                             t.IsBackground=true;
                             t.Priority=ThreadPriority.BelowNormal;
                             t.Start();
                   catch (System.Exception e1)
                   {  Console.WriteLine("An Exception Occurred while Listening :" +e1.ToString()); }
    As mentioned above There are mostly some Word-Documents or PDF files send as the body of a request. So I need to parse the body and write the content to a file.
    Currently I use this code to accomplish that:
         while (true)
             if(socket.Available == 0)
              break;
                n = socket.Receive(bytes);
             if(n == 0)
               break;
             wr.Write(bytes,0,n); // wr is a BinaryWriter
    Now my problem is that this loop breaks before all data is received from the socket. That means it runs into the socket.Available == 0 case and ends, but there is still data available. How did I find that out? Well during debugging the code.
    With the debugger running and when stepping through the code, obviously leaves the SAP side more time to send its data.
    When doing some Console.WriteLine() after the loop with the socket.Receive() I get results > 0. So there is still data available.
    I am not asking an SAP question here. I am aware that the problem could also be on the SAP side. However I think it is a C# issue. Has anyone experienced similar problems with sockets? Am I doing something completely wrong in handling my socket? I also don´t think that I can use Asynchronous sockets beacuse I need to process incoming requests in a determined order.
    I have also tryed to turn off Blocking mode by setting socket.Blocking = false but I found out that I cannon use that because I need NetworkStream at some point in my application and NetworkStream does not work without blocking mode.

    I have evaluated several other possibilities before starting to implement HTTP on a socket basis. I only have this choice.
    I have had a detailed look at Cassini before, but since you mentioned it in your post I looked at it more closely and I think I found a solution for my Problem.
    Cassini uses some code like the following to poll for more data in a request. I am now using this mechanism in my application and it works fine.
              private int WaitForRequestBytes()
                   int availBytes = 0;
                   try
                        Console.WriteLine("socket.Available: " + socket.Available);
                        if (socket.Available == 0)
                             // poll until there is data
                             Console.WriteLine("Polling 100ms");
                             socket.Poll(100000 /* 100ms */, SelectMode.SelectRead);
                             if (socket.Available == 0 && socket.Connected)
                                  Console.WriteLine("Polling 1sec");
                                  socket.Poll(1000000 /* 1sec */, SelectMode.SelectRead);
                                  // socket.Poll(10000000 /* 10sec */, SelectMode.SelectRead);
                        availBytes = socket.Available;
                   catch
                   return availBytes;
    So thanks for putting me in the right direction.
    Mirco

  • TCP Socket Adapter

    I want to use BPEL to integrate Oracle CRM with some banking software that validates bank sort codes and account numbers. The banking validation software listens for an input stream on a TCP socket.
    Can anyone tell me where I can find the technology socket adapter that are referenced on a number of Oracle presentations?
    I know I could write code in Java to achieved the same effect, but if there is an adapter that can do the job then that is preferable.

    I too am looking for this. I see that one of the posters above mentions an item provided by oracle, more details would be appreciated.
    In the mean time, I think the way to go is to write a POJO that sits on the the tcp port and gets into the ESB via a message queue, allowing it to "send an event" if you will.
    The scenario where you want to go outbound to tcp might be a bit trickier, if I use the POJO approach, then my code is outside of the ESB, since the ESB would end by dumping to a message queue, and my POJO would pick up from there.
    It would be really nice to have an Oracle component specificially for TCP.

  • TCP sockets on MIDP over GPRS

    Extending the CLDC socket.Protocol class I can make a TCP socket connection from a MIDlet. I'm hoping to market my application on GPRS networks, but I'm not sure that it supports TCP connections. I've read that TCP runs on circuit switching networks, and UDP on packet switching networks. I think GPRS is the latter. I need to maintain a constant, "connection-oriented" socket - i.e. TCP. Does anyone happen to know whether TCP/IP will function properly over GPRS? I realise this is why MIDP only implements HTTP and not raw sockets, but I thought it was worth asking anyway. Any help at all would be greatly appreciated.

    Hi Briggsd!
    I'm playing with some sockets.
    can you please help me?!
    J2ME uses only HTTP connections?
    and what are the sockets? what is the difference between CLDC socket and J2SE Socket?
    is there any other way to communicate with a Servlet?
    and very important..
    is there a difference if it's using GPRS or 3G?
    would the http connection work for all? and just the connection speed would change?
    help me!!

  • TCP Socket connection in CLOSE_WAIT status and not getting closed

    I am facing an issue with the TCP socket connections not getting closed and they are in CLOSE_WAIT status for ever.
    As a part of batch process in our application, emails are sent with 4 embedded images. These images are downloaded from 3rd party site with IP say "UUU.XXX.YYY.ZZZ"
    The images are embedded to email as follows
    1. An URL object is created with the site url.
    URL urlPhoto = new
    URL("http://UUU.XXX.YYY.ZZZ/email/photos.jpg");
    2.     The image cid is created with the URL object and the image name
    HtmlEmail htmlEmail = new HtmlEmail();
    String cid1 = htmlEmail.embed(urlPhoto,
    "photo.jpg");
    3.     The image cid is added to the email template by replacing the ${cid1} and the email is sent.
    <td valign="top">
                   <img src="cid:${cid1}" width="279" height="274">
              </td>
    When a mail is sent, 4 new TCP connections are opened and are put in CLOSE_WAIT status for ever. For every mail sent 4 new connections are opened. In UNIX there is an upper limit on the number of open file handles (defaults to 1024) at any point of time. The open TCP connection has the underlying socket in CLOSE_WAIT status and is not getting closed at all. When the upper limit (1024) is reached the batch process is throwing the following exception and terminates.
    Caused by: com.inet.tds.ap: java.net.SocketExceptionjava.net.SocketException: Too many open files
    at com.inet.tds.am.a(Unknown Source)
    at com.inet.tds.TdsDriver.a(Unknown Source)
    at com.inet.tds.TdsDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:525)
    at java.sql.DriverManager.getConnection(DriverManager.java:171)
    at com.hcomemea.batchprocess.dataaccess.database.BaseJdbcDao.openConnection(BaseJdbcDao.java:106)
    ... 12 more
    When I run the command lsof in UNIX which list the open file handles in the system
    $ /usr/sbin/lsof -p 22933 -i | grep CLOSE_WAIT
    java 22933 build_master 297u IPv6 129841943 TCP integration.com:47929->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 298u IPv6 129841947 TCP integration.com:47933->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 299u IPv6 129841950 TCP integration.com:47936->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    java 22933 build_master 300u IPv6 129841970 TCP integration.com:47952->UUU.XXX.YYY.ZZZ:http (CLOSE_WAIT)
    ���list of 935 connections similarly�
    I tried 2 solutions
    1. Got the HttpURLConnection from the URL object and invoked disconnect method on the same. But it doesn�t work.
    2. Ran the batch process java program with the parameter �Dhttp.keepAlive=false to close the underlying connection but didn�t help.
    I need the underlying sockets to be closed and not put in CLOSE_WAIT status after sending the mail.
    Is it the problem with the embed method of HtmlEmail object not closing the underlying socket connection.
    If anyone has faced this issue before, kindly let me know the possible solutions for the same ASAP.
    Thank you,
    Ramesh G

    This sounds more like a problem due to connection pooling at middle tier/application server.
    If that has been ruled out, then you might to enable DCD or set expiry time on the server.

  • Reading input stream over the tcp socket in unix

    I have a program that reads data from input stream from the socket. If the data is over 1500 bytes it is sent in multiple TCP packets. Whats weird is, if I run the program in windows environment it waits till it receives all the packets but when I run the same program in unix environment it only reads the first packet and go further without waiting for all the TCP packets!!
    The line that reads from input stream is
    datalen = inStr.read(byteBuffer);is there anyway I can make it wait till it receives all the packets on unix system? I do not understand why it works fine for windows in this case but not for unix.
    I'll appreciate any help..
    Thanks

    When the network is busy there can be any amount of dleay between packets. If this is ever 100 ms , then this will break.
    If you send more than one packet per 100 ms you will get two packets at once which will look like one longer packet. Unless you check for this the second packet may get ignored.
    The safe way is to send the packet size before sending the packet. Then on the client read the packet to the correct length. Otherwise you will have a program which just happens to work rather than one which will always work.

  • Receiving data through TCP Socket

    Hi all,
    I am trying to receive some data through TCP Socket from the
    server using XMLSocketClass. Ther server is responding with some
    data. But I can't access this data in my application. Pls tell me
    the reasons for not working of handler private function
    dataHandler(event:DataEvent):void .
    =============================================================================
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.collections.ArrayCollection;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.DataEvent;
    import flash.events.IOErrorEvent;
    import flash.net.XMLSocket;
    private var socket:XMLSocket;
    private var nextId:int;
    private var events:ArrayCollection = new ArrayCollection();
    public static var host:String = "34.234.43.97";
    public static var port:Number = 8002;
    public var xml:XML;
    private function connectToServer():void
    socket = new XMLSocket();
    socket.addEventListener(DataEvent.DATA, dataHandler);
    configureListeners(socket);
    socket.connect(host, port);
    //This function is Not working
    private function dataHandler(event:DataEvent):void {
    Alert.show("dataHandler: " + event.data);
    xml = new XML(event.data);
    Alert.show(xml); }
    private function
    configureListeners(dispatcher:IEventDispatcher):void {
    dispatcher.addEventListener(Event.CLOSE, closeHandler);
    dispatcher.addEventListener(Event.CONNECT, connectHandler);
    dispatcher.addEventListener(DataEvent.DATA, dataHandler);
    dispatcher.addEventListener(IOErrorEvent.IO_ERROR,
    ioErrorHandler);
    dispatcher.addEventListener(ProgressEvent.PROGRESS,
    progressHandler);
    dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
    securityErrorHandler);
    private function closeHandler(event:Event):void {
    trace("closeHandler: " + event);
    private function ioErrorHandler(event:IOErrorEvent):void {
    trace("ioErrorHandler: " + event);
    private function progressHandler(event:ProgressEvent):void {
    trace("progressHandler loaded:" + event.bytesLoaded + "
    total: " + event.bytesTotal);
    private function
    securityErrorHandler(event:SecurityErrorEvent):void {
    trace("securityErrorHandler: " + event);
    /* private function dataHandler(event:DataEvent):void {
    trace("dataHandler: " + event);
    private function connectHandler(event:Event):void
    var obj:Object = new Object();
    obj.id = nextId++;
    obj.eventName="connect";
    obj.timestamp = new Date().valueOf();
    events.addItem(obj);
    private function sendData():void
    var xmlvalue:String=txtData.text.toString() ;
    var xmlfile:String =
    "<command>SndIns<parameter1>0x06</parameter1><parameter2>0x00</parameter2><parameter3>0x7 1</parameter3><parameter4>0x0F</parameter4><parameter5>0x11</parameter5><parameter6>0xFF</ parameter6></command>";
    socket.send(xmlfile);
    Alert.show(xmlfile);
    ]]>
    </mx:Script>
    <mx:HBox width="80%" horizontalAlign="center">
    <mx:TextInput id="txtData" name=""/>
    <mx:Button id="btnConnect" label="Connect"
    click="connectToServer();btnConnect.enabled = false"/>
    <mx:Button id="btnSend" label="Send Data"
    click="sendData()"/>
    <!--<mx:Button label="getData" id="btnGet"
    click="getData()"/>-->
    </mx:HBox>
    <mx:HBox x="10" y="30" width="100%">
    <mx:DataGrid width="80%" height="100%"
    dataProvider="{xml}">
    <mx:columns>
    <mx:Array>
    <mx:DataGridColumn headerText="Event Name"
    dataField="eventName"/>
    </mx:Array>
    </mx:columns>
    </mx:DataGrid>
    </mx:HBox>
    </mx:Application>

    Hi all,
    I am trying to receive some data through TCP Socket from the
    server using XMLSocketClass. Ther server is responding with some
    data. But I can't access this data in my application. Pls tell me
    the reasons for not working of handler private function
    dataHandler(event:DataEvent):void .
    =============================================================================
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.collections.ArrayCollection;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.DataEvent;
    import flash.events.IOErrorEvent;
    import flash.net.XMLSocket;
    private var socket:XMLSocket;
    private var nextId:int;
    private var events:ArrayCollection = new ArrayCollection();
    public static var host:String = "34.234.43.97";
    public static var port:Number = 8002;
    public var xml:XML;
    private function connectToServer():void
    socket = new XMLSocket();
    socket.addEventListener(DataEvent.DATA, dataHandler);
    configureListeners(socket);
    socket.connect(host, port);
    //This function is Not working
    private function dataHandler(event:DataEvent):void {
    Alert.show("dataHandler: " + event.data);
    xml = new XML(event.data);
    Alert.show(xml); }
    private function
    configureListeners(dispatcher:IEventDispatcher):void {
    dispatcher.addEventListener(Event.CLOSE, closeHandler);
    dispatcher.addEventListener(Event.CONNECT, connectHandler);
    dispatcher.addEventListener(DataEvent.DATA, dataHandler);
    dispatcher.addEventListener(IOErrorEvent.IO_ERROR,
    ioErrorHandler);
    dispatcher.addEventListener(ProgressEvent.PROGRESS,
    progressHandler);
    dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
    securityErrorHandler);
    private function closeHandler(event:Event):void {
    trace("closeHandler: " + event);
    private function ioErrorHandler(event:IOErrorEvent):void {
    trace("ioErrorHandler: " + event);
    private function progressHandler(event:ProgressEvent):void {
    trace("progressHandler loaded:" + event.bytesLoaded + "
    total: " + event.bytesTotal);
    private function
    securityErrorHandler(event:SecurityErrorEvent):void {
    trace("securityErrorHandler: " + event);
    /* private function dataHandler(event:DataEvent):void {
    trace("dataHandler: " + event);
    private function connectHandler(event:Event):void
    var obj:Object = new Object();
    obj.id = nextId++;
    obj.eventName="connect";
    obj.timestamp = new Date().valueOf();
    events.addItem(obj);
    private function sendData():void
    var xmlvalue:String=txtData.text.toString() ;
    var xmlfile:String =
    "<command>SndIns<parameter1>0x06</parameter1><parameter2>0x00</parameter2><parameter3>0x7 1</parameter3><parameter4>0x0F</parameter4><parameter5>0x11</parameter5><parameter6>0xFF</ parameter6></command>";
    socket.send(xmlfile);
    Alert.show(xmlfile);
    ]]>
    </mx:Script>
    <mx:HBox width="80%" horizontalAlign="center">
    <mx:TextInput id="txtData" name=""/>
    <mx:Button id="btnConnect" label="Connect"
    click="connectToServer();btnConnect.enabled = false"/>
    <mx:Button id="btnSend" label="Send Data"
    click="sendData()"/>
    <!--<mx:Button label="getData" id="btnGet"
    click="getData()"/>-->
    </mx:HBox>
    <mx:HBox x="10" y="30" width="100%">
    <mx:DataGrid width="80%" height="100%"
    dataProvider="{xml}">
    <mx:columns>
    <mx:Array>
    <mx:DataGridColumn headerText="Event Name"
    dataField="eventName"/>
    </mx:Array>
    </mx:columns>
    </mx:DataGrid>
    </mx:HBox>
    </mx:Application>

  • Persistent TCP socket trouble

    Hello everybody!
    I'm writing a server/client chat app, mostly for fun but I actually have some use for it as well, when it works that is.
    The server part is pretty much complete, written in Python (since it's so easy and fast to write).
    Anyway, since my chat protocol is supposed to use as little bandwidth as possible, I'm aiming for persistant TCP connections. To make that possible, I've implemented an end of message-marker, so that it reads until it finds the marker, and that's the end of the transmission, instead of reading until the socket is closed and a new connection needs to be reestablished all the time.
    My problem is that I have no idea how to implement this in java! Not in python either to be honest, I used the code from here, although with a few slight modifications:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408859
    (the recv_end function)
    For those who don't understand python, it reads 8kB from the socket, checks in the end marker is in there. If not, it checks if the end market got split between multiple packets, and concatenates everything until the original string is restored.
    Now, I need to do this in java (J2ME/MIDP 2.0 to be exact, but if I get some code to work with I'm sure I can make it work).
    I've got this code in my app, that needs to be replaced:
         protected synchronized StringBuffer read ()
              StringBuffer sb = new StringBuffer();
              int i = 0;
              try
                   while (((i = input.read()) != -1))
                        sb.append((char)i);
              catch (Exception e){}
              finally
                   return sb;
         }I'd be glad to post more code or explain more throughly if needed.
    Other ideas might be welcome as well.
    Help would be very appreciated!

    I've solved it, well kinda anyway. :)
    Not the most effective solution, but since I doubt
    that transmissions >1kB will ever be sent/received
    using this program, it doesn't matter that much.
    This is what I did:
         protected StringBuffer read ()
              StringBuffer soFar = new StringBuffer();
    int r = 0;
              while (true)
                   try
                        r = input.read();
                   catch (Exception e)
                        System.out.println(e.toString());
                   if (r != 4)
                        soFar.append((char)r);
                   else
                        return soFar;
    Surely somewhere in that code you will also need
    r++;

  • Close socket hangs in SunOS5.6

    The close() function is hanging when I attempt to close a socket. I have a small multi-threaded program, which I will attach below, which replicates the problem. Basically, the program creates a thread which listens for a datagram from a socket using the recvfrom() function. When the main thread attempts to close the socket being listened to, the close() function never returns. My guess is the recvfrom() function is doing some kind of blocking and somehow needs to be told to quit waiting. However, I'm not sure how one does this. Any ideas are greatly appreciated.
    Sun tech. support recommended installing some patches we are missing. While that may ultimately be the solution, I would like to avoid doing so because this would affect multiple products we are developing and many of our customers.
    The related portion of the code is:
    main()
    /* create thread using pthread_create() */
    while (1) {
    fgets(c, sizeof(c), stdin);
    if (c[0] == '\n')
    break;
    fprintf(stderr, "Closing socket\n");
    close(sockfd);
    exit(0);
    void wait_awhile(void) {
    char buff[MAXLINE];
    int n;
    fprintf(stderr, "\nIN THREAD: prior to socket call\n");
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
    fprintf(stderr, "could not create socket\n");
    exit(0);
    /* Get the server's socket address */
    bzero((struct sockaddr_in *)&servaddr, sizeof(servaddr));
    clientaddr_len = sizeof(struct sockaddr_in);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(3500);
    servaddr.sin_addr.s_addr = inet_addr(ip_address);
    /* Bind it to the port */
    fprintf(stderr, "IN THREAD: Binding socket\n");
    if (bind(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
    close(sockfd);
    fprintf(stderr, "could not bind socket\n");
    exit(0);
    while (1)
    fprintf(stderr, "IN THREAD: Waiting for datagram\n");
    if ( (n = recvfrom(sockfd, buff, MAXLINE, 0, (SA *)&clientaddr, &clientaddr_len)) < 0)
    close(sockfd);
    }

    "Shirley" <[email protected]> wrote:
    >
    "Khalid" <[email protected]> wrote:
    We seem to have close wait problem in extreme load where apache/weblogic
    hold the
    tread so the socket cannot be closed. Does anyone know how to fix this
    problem.
    It seems like after in runs out of thread the server crashes.
    Have you fixed this problem you were facing ,because we are facing exactly
    the
    same problem.Did you find any solution .If so please do let us know
    Cheers
    Shirley RemediosWe had the same problem and reduced the number of sockets in this state by reducing
    the time to wait before closing the sockets. On Solaris we set 'tcp_time_wait_interval'
    to 30000 (30 seconds) on the web and app servers.

  • Error 63 and 60 from TCP Listen.vi

    Hi All,
    I got error 63 from TCP listen.vi and error 60  from retry.
    Any idea of that?
    Thanks a lot for any help.
    Anne

    The consequent error 60 is quite likely caused by the fact that Winsock does not close a socket immediately in order to handle lingering packets that might still be arriving for that socket. So your Listen tries to open a socket, but somehow gets refused that socket, but it has been allocated anyhow in the Winsock library and eventhough LabVIEW closes the socket (you do executed a TCP Close node even on error on the listen refnum do you?? ) Winsock needs some time to really deallocate that socket, and when you immediately retry the port is still in use.
    Make sure to always close all refnums, also the listener refnum, even in error case and if that does not help add some delay before retrying to open the Listener again.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Using SMTP I can not use a mail server with more than 13 characters. I get an error from TCP open

    I have no trouble sending an email if the mail server name is less than 13 characters long. I get an error 54 from TCP open when it exceeds that length. How do I get around this?

    Don't know what to say, I just tried the SMTP email VI I have with an 18-character mail server address and everything worked fine. The error 54 means that the address is ill-formed.
    The only thing I would suggest is trace the mail-server address down through the hierarchy and make sure nothing is done to modify it. Also try putting a probe on the wire going into the TCP open function and make sure the string you see there is the same one you are using. Finally, change the formatting of the control taking the address into the subvi that contains the TCP open function (SMTP Open Session.vi)to show the slash codes and make sure some invisible characters aren't getting added along the way.
    As a last resort save the vi in 6.0 format and send it to me and I'll
    try it on my system--maybe there's something screwy going on with your computer...
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Which load testing tool is appropriate for sending message to a tcp socket

    Hi,
    I am new to the testing world. I have developed a messaging application, where the client sends his requests on to the server program which opens a socket and listens for messages. Then all mesaging goes on. I want to load test my application. I have tested it with Apache's JMeter, besides that are there any other load testing tools.
    The clients need to send messages on a tcp socket. I really need this, please help me.
    Thanks,

    Dude,
    Write one!
    I test any servers I've written by hammering them by writing a multi-threaded test program to simulate client activity, namely an initial login and then whatever other activity the client would usually perform. Maybe in your case this would involve the sending of messages, the checking/reading of new messages and logging out.
    I usually get my timing statistics by simply capturing a start time and an end time (the difference being the m/s taken). ie: using java.util.Date.
    Run the test program from a single host to iron out any initial problems, but then be sure to run it from as many different hosts as you can get your mitts on!

  • Communication with database using TCP sockets connection

    Hi all,
    I am bit of a newbie when it comes to databases. In a project I realised over te passed few weeks, I communicated with an 11g database using an application I created with VS Express. It uses an ODBC connection. I now want to connect a PLC to the same database. These PLC's don't have the ability to install an ODBC client so I need something different.
    I am easily able to open a TCP socket on the PLC and send data from there. I would like to know if I can start a TCP sockets connection with our 11g server and send all queries directly. The other (already suggested) option would be to have the PLC connect to a PC that reads this information and hands it over to the ODBC connector, but that would mean I need an extra PC just to 'translate'.
    I have been searching these forums for socket, TCP and more and feel it is possible, but I need a good document as a reference to show/tell me how it's done.
    Thanks in advance,
    Marijn

    The TCP/IP interface to Oracle is undocumented (and hugely complex anyway). You'll need to use a higher layer iterface or setup your own infrastructure.
    We need more information about what is available to you inside the PLC.
    Can you use Java? If so, perhaps use thin JDBC?
    Can you sent HTTP requests? If so you could set up your own Web services to handle this.
    If you can only use C or C++, Oracle has interfaces there too.. it's called OCI (Oracle Call Interface) and thats as close to the networking layer as you can get.
    Finally if you can use .NET Oracle has a Fully Managed Oracle Data Provider for .NET that you could use.
    But if all you can do is super low level network access and none of the above then you will need to set up an intermediary as you mentioned.

Maybe you are looking for

  • Error 500 when trying to upload PAR file from NWDS

    Since few weeks now, I'm not able to directly upload a par file from NWDS. I'm always getting a operation failed error. In the sap-plugin.log file I've found the following trace: [21.04.09 / 17:51] #ERROR LEVEL# com.sap.portal.developmentTools.ideSpe

  • Macromedia Contribute 3.11 Slow Connection issues Windows 7

    I have got Macromedia Contribute 3.11, i am experiencing lot of issues at the moment. Firstly, it takes a long time to connect to the server, most of the times it connects to the server, sometimes it fails, but the time it takes to connect to the ser

  • Debit memo

    hi, i need clarification from the post. 1) suresh kumar : dont put head ache of debit memo may i know what does it mean? 2) tracy meng : in sap, we normally do credit memo for vendor and cust. may i know why no debit memo? 3) when issue credit memo t

  • 8310, MicroSDHC card & Media loading issues !

    Hi, My first post & a query!! I have an 8310 provided by my work, and because it is provided by them (via O2) there seem to be a few things locked on it to minimise our tampering!  ...... I have purchased an 8gb Micro-SDHC card for it with the intent

  • Restart OC4J as part of Auto deploy

    I was trying to implement AutoDeploy of EAR file on daily basis, the plan is to use ANT script to generate the EAR file, Deploy the EAR file and restart the OC4J to reflect the new EAR file. I was trying to use ANT task shutdownServer and restartServ