BufferedReader.readLine() from a socket repeats input (JDK 1.4 beta/Win95)

When I call BufferedInput.readLine(), and the data source is a socket, readLine()
will return the most recent text indefinitely until the client sends more text.
Isn't BufferedInput.readLine() supposed to clear the
buffer with each readLine() call?
Socket settings:
getTcpNoDelay: false
getSoLinger: 10
getSoTimeout: 75
getSendBufferSize: 8192
getReceiveBufferSize: 8192
Locations of complete source and output:
http://www.nationalinformatics.com/download/SocketServerClientTest.java
http://www.nationalinformatics.com/download/SocketServerTest_output.txt
http://www.nationalinformatics.com/download/SocketServerTest.java
http://www.nationalinformatics.com/download/SocketServerClientTest.java
http://www.nationalinformatics.com/download/SocketServerClientThread.java
</PRE>
Sample output:
SocketServerThread: readline loop.
SocketServerThread: Input line is 'hello' (length: 5)
SocketServerThread: input line was read
SocketServerThread: readline loop.
SocketServerThread: Input line is 'hello' (length: 5)
SocketServerThread: input line was read
. . . etc, until the client sends "Java Rules!" down the wire . . .
SocketServerThread: readline loop.
SocketServerThread: Input line is 'Java Rules!' (length: 11)
SocketServerThread: input line was read
SocketServerThread: readline loop.
SocketServerThread: Input line is 'Java Rules!' (length: 11)
SocketServerThread: input line was read
. . . etc . . .
Thread code that reads input from the client:
import java.net.*;
import java.io.*;
import java.util.*;
/** SocketServerThread is an independent thread that is used to test
    socket connections.
    <p>Copyright 2001 (c) Richard Schilling.  All rights reserved.
class SocketServerThread extends Thread {
     private boolean running;
        private Socket socket = null;
        public SocketServerThread(Socket s, boolean r) {
                socket = s;
          running = r;
        public void run() {
                try {
                        // Create a reader to receive messages from the client
                        BufferedReader in = new BufferedReader(
                                 new InputStreamReader(socket.getInputStream())
                        String inputLine = null;
                        while ( running) {
                    System.out.println("SocketServerThread: readline loop.");
                    boolean lineread = false;
                    while (!lineread){
                         lineread = true;
                         try {
                              inputLine = in.readLine();
                         } catch (InterruptedIOException e){
                              lineread = false;
                              System.out.println("SocketServerThread: Interrupted exception while reading from 'in'");
                         } catch (SocketException e){
                              lineread = false;
                              System.out.println("SocketServerThread: could not read input stream 'in'");
                    if (inputLine != null){
                         if (inputLine.length() > 0){
                              String TrimmedInputLine = inputLine.trim();
                              System.out.println("SocketServerThread: Input line is '" + TrimmedInputLine + "' (length: " + TrimmedInputLine.length() + ")");
                                                /* Process the string that has been received from the client.
                              System.out.println("SocketServerThread: input line was read");
                                                if (TrimmedInputLine.equalsIgnoreCase("bye")){
                                   running = false;
                    else{
                              // set the status of this thread so that it closes the connection and exits.                              
                              running = false;
                    inputLine = null;
                                yield();
                        in.close();
                        System.out.println("SocketServerThread: CONNECTION WITH CLIENT CLOSED");
                } catch (IOException e) {
                        e.printStackTrace();

Sounds like a bug to me. Do the other read() methods work as expected? I suppose you could compare the source from JDK1.3 with the source from JDK1.4 and see if something changed.
Worst case write your own method. I had to write one for J2ME since they decided that functionality wasn't important. grr.
Good luck.

Similar Messages

  • ReadLine() from a socket

    I have a BufferedReader attached to a socket, and I have an infinite loop for waiting on messages that looks something like this:
    <String message was declared somewhere above>
    while(true)
    try{
    message=socketIn.readLine();
    System.out.println(message);
    catch(IOException e)
    System.out.println("Something didn't work.");
    System.exit(1);
    //other stuff happens down here
    (For the record, this is part of an IRC connector that waits for a reply before sending the next login command.)
    The problem is that the program seems to hang here. I've changed it to catch any exception, even though I don't think anything in the try block can throw anything besides IOExceptions; I've tried adding a counter to see how many times it goes through; etc. It seems that when it gets to the readLine() statement, it just stops. Does readLine on a socket wait for input? Or is there just something very, very wrong with my code?
    Thanks for any help.

    I always use this code From a website.
    It works like a dream
    /* StringIO does the job of converting a socket into*/
    /* a pair of byte input/output streams.  Since this */
    /* is such a common (and tedious) thing to write,   */
    /* it is done once, here, to be reused.             */
    import java.io.*;
    import java.net.*;
    class StringIO {
       public BufferedReader   in;
       public DataOutputStream out;
       public Socket           sock;
       void errorExit() {
             System.err.println("Couldn't open input/output streams");
             System.exit(1);
       public StringIO( Socket s ) {
          try {
             sock = s;
             in  = new BufferedReader( new InputStreamReader(
                                       s.getInputStream() ));
             out = new DataOutputStream( s.getOutputStream() );
          } catch (IOException e) {
             errorExit();
          if (in == null || out == null)
             errorExit();
       public StringIO( GenericClient gc ) {
          this( gc.s );
       public void close() {
          try {
             in.close();
             out.close();
             sock.close();
          } catch (IOException e) {
             System.err.println("Cannot close i/o streams or socket");
    }Hope this helps

  • Fetching a URL  from a socket output or input stream in a proxy server

    We have written a proxy server in java .
    It connects with a client on some local port and forwards the request of the client to main server through socket connections.
    The code is as follows...
    * BasicProxyServer.java
    * A simple multithreaded proxy server.
    * A client connects to theserver. The server starts a
    * separate threads for data flow though two Sockets.
    * The first socket communicates with the socket of the client.
    * The second socket is used to communcate with the main server
    * for which this server is a proxy. The sockets are connected by pipes.
    import java.net.*;
    import java.io.*;
    public class BasicProxyServer {
         private static int serverPort;
         private static String primaryServerHost;
         private static int primaryServerPort;
         // 1st arg: port to listen on
         // 2nd arg: primary server IP
         // 3rd arg: primary server port
         public static void main(String [] args) {
              serverPort = Integer.parseInt(args[0]);
              primaryServerHost = args[1];
              primaryServerPort = Integer.parseInt(args[2]);
              BasicServer bserv = new BasicServer(serverPort,primaryServerHost,primaryServerPort);
    class BasicServer extends Thread {
         private int serverPort;
         private String primaryHost;
         private int primaryPort;
         private ServerSocket servSock = null;
         public BasicServer(int port, String primSrv, int primPort) {
              serverPort = port;
              primaryHost = primSrv;
              primaryPort = primPort;
              start();
         public void run() {
              Socket clientSock = null;
              Socket primaryServerSock = null;
              try {
                   servSock = new ServerSocket(serverPort);
              catch (IOException e) {
                   e.printStackTrace();
              while(true) {
                   try {
                        clientSock = servSock.accept();
                        primaryServerSock = new Socket(primaryHost, primaryPort);
                        PipedInputStream fromClient = new PipedInputStream();
                        PipedOutputStream toMainServer = new PipedOutputStream(fromClient);
                        PipedInputStream fromMainServer = new PipedInputStream();
                        PipedOutputStream toClient = new PipedOutputStream(fromMainServer);
                        Talk clientToMainServer = new Talk(clientSock, fromClient, primaryServerSock, toMainServer);
                        Talk mainServerToClient = new Talk(primaryServerSock, fromMainServer, clientSock, toClient);
                        clientToMainServer.start();
                        mainServerToClient.start();
                   catch (IOException e) {
                        e.printStackTrace();
         // Override finalize() to close server socket
    protected void finalize() {
    if (servSock != null) {
    try {
    servSock.close();
    } catch (IOException e) {
    e.printStackTrace();
    servSock = null;
    class Talk extends Thread {
         private Socket incoming;
         private Socket outgoing;
         private InputStream in;
         private OutputStream out;
         private InputStream from;
         private OutputStream to;
         Talk(Socket inSock, InputStream in, Socket outSock, OutputStream out) {
              this.in = in;
              this.out = out;
              incoming = inSock;
              outgoing = outSock;
         public void run() {
              int aByte;
              try {
                   from = incoming.getInputStream();
                   to = outgoing.getOutputStream();          
                   while(( aByte = from.read()) != -1 ) {     //read from socket
                        out.write(aByte);     // write to pipe`
                        // read the byte from the pipe
                        to.write(in.read());          // write it to the output socket stream
                        to.flush();
                   to.close();
                   from.close();
                   if(incoming != null) {
                        incoming.close();
                        incoming = null;
                   if(outgoing != null) {
                        outgoing.close();
                        outgoing = null;
              catch (SocketException e) {
              // there is one for a closed socket. Seems to have no effect.
              //     e.printStackTrace();
              catch (IOException e) {
                   e.printStackTrace();
    Here,when client gives any URL in the address bar in the web browser the request is forwarded to this proxy server.
    We want to fetch the URL which client enters in order to implement content filtering and also store the most visited sites by each user .
    But we don't know how to fetch the URL from the socket input or output stream.
    Can you suggest any suitable solution for the same??

    Shailesh24 wrote:
    We want to fetch the URL which client enters in order to implement content filtering and also store the most visited sites by each user .
    But we don't know how to fetch the URL from the socket input or output stream.
    Can you suggest any suitable solution for the same??Yes. Write a proxy server that actually speaks HTTP.

  • Parsing input stream from a socket

    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    Thanks,
    Andrea

    andmus wrote:
    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    If you're reading HTTP...
    Unless the request has been sent with Connection: close, it's normal that your read blocks, since the connection is purposefully left open to accomodate further exchanges.
    You'll have to parse the data to know when each message is complete. The first empty line (bytes: \r\n\r\n ASCII) denotes the end of the header. The header will have a Content-Length property which tells you how many bytes are left to read.
    Google the HTTP specs if you don't know them.

  • Bug with InputStream.read after BufferedReader.readLine in a Thread ?

    I just found something strange when reading bytes on a socket after reading lines.
    I'll show you an example :
    In this example, when a connexion is established, I launch a thread where a single line of String then 3 bytes are read from the socket. I use BufferedReader.readLine for the String line then just InputStream.read to read the 3 bytes.
    The results are quite random. Sometimes it works, sometimes not (most times it doesn't)... it seems to always work under linux (but haven't tested it as many times than on windows). Most of the time the program is stuck on the "socket.getInputStream().read(bytes);" line with 0 bytes available. I tried to do the same thing outside of a thread, I thought it worked better beaucause I was able to run it without any problem but it doesn't work anymore when I test it again.
    I can't say if I'm doing something wrong or if it's a java bug (I've got JDK 1.6.0_03-b05).
    Can you please have a look a this little example and maybe test it and let me know if it works or not. I tried to code my own readLine function and it seems to work with it but I'd like to know if it's a bug or what. Thank you.
    Server side :
    import java.io.*;
    import java.net.*;
    public class testServer extends Thread {
         private Socket socket;
         public testServer(Socket testSocket)
              socket = testSocket;
         public void readData() throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String str;
              str = br.readLine();
              System.out.println(str);
              System.out.println("Bytes available : " + socket.getInputStream().available());
                    //Try to read the bytes
                    byte[] bytes = new byte[3];
                    //STOPS THERE UNDER WINDOWS, BUT WORKS WITH LINUX
              socket.getInputStream().read(bytes);
                    //Simple "ack" to say to the client that he can close the connexion
              socket.getOutputStream().write(0);
              socket.getOutputStream().flush();
                    //Print the bytes values
              for(byte value : bytes)
                   System.out.println(value);
         public void run()
              try {
                   readData();
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   ServerSocket welcomeSocket = new ServerSocket(3333);
                   while(true)
                        new testServer(welcomeSocket.accept()).start();
              } catch (Exception e) {
                   e.printStackTrace();
    }client side :
    import java.io.*;
    import java.net.*;
    public class testClient {
         public static void main(String[] args) {
              try {
                            //Some test values
                   byte[] testValues = new byte[]{1,2,3};
                   Socket socket = new Socket(InetAddress.getLocalHost(), 3333);
                            //Send the line through the socket
                   BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   bw.write("HELLO WORLD\r\n");
                   bw.flush();
                            //then the bytes
                   socket.getOutputStream().write(testValues);
                   socket.getOutputStream().flush();
                            //Just waits for the server's ack to close the connexion
                   socket.getInputStream().read();
                   socket.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    It's your bug.
    When you create a BufferedReader and ask it to read a line, the first thing it does is to read a whole buffer full of data (hence the name of the class) from its underlying input stream. That's probably about 4000 characters or something like that. It stores that internally and then starts doling it out in response to calls to readLine() and so on.
    Then when you go back to reading from the underlying input stream, those 4000 or so characters are already gone from it. You have no access to the data the BufferedReader is hanging on to this way. All you can do is to start reading at the point after that whole buffer, which is not what you want.

  • 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

  • Trying to read from a socket character by character

    Hi all,
    I have a problem with reading from a socket character by character. In the code shown below I try and read each character, and then write it to a file. The information sent to a socket sent from a file, and EOF is marked with character of ascii code 28 (file separator). However using BufferedReader.read() I get -1 forever. Is it reading only the last character to have been sent to the socket?
    As a side note, if I use readLine() (making sure the socket is sent a newline at end of msg) I can get the message fine. However, I want to be able to receive a message with 0 or many newlines in it (basically contents of a text file), so I want to avoid the readLine() method.
    Any help at all is appreciated,
    Colm
    CODE SNIPPET:
    try
    serverSocket = new ServerSocket(listenToPort);
    System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
    while(true)
    inSocket = serverSocket.accept();
    System.out.println("New connection accepted " + inSocket.getInetAddress() + ":" + inSocket.getPort());
    input = new BufferedReader(new InputStreamReader(inSocket.getInputStream()));
    fileOutput = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Ready to write to file: " + outputFilename);
    //receive each character and output it to file until file separator arrives
    while(!eof)
    inCharBuf = input.read();
    System.out.print(inCharBuf);
    //check for file separator (ASCII code 28)
    if (inCharBuf == 28) eof = true;
    //inChar = (char) inCharBuf;
    fileOutput.write(inCharBuf);
    System.out.println("Finished writing to file: " + outputFilename);
    inSocket.close();
    catch (IOException e)
    System.out.println("IO Error with serverSocket: " + e);
    System.exit(-1);
    }(tabbing removed as it was messing up formatting)

    My guess is that the code that is writing to the
    socket did not flush it. You said in one case you
    could read it (via readln) if the writer was writing
    lines (writeln flushes, I believe). Are you writing
    the exact same data to the socket in both tests?woo hoo, I hadn't flushed the buffers alright!
    for anyone with similar problems, I was missing this from my write-to-socket method:
    output.flush();
    where output was the BufferedWriter I had created to write to the socket.
    Thanks a lot for pointing it out!
    Colm

  • 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.

  • Reading from a socket that requires an EOF.

    I'm trying to send a request and get a response from a socket.
    The server only seems to send the response once it gets an EOF. The only way I can seem to get an EOF is to close my output stream. However, when I close my output stream before reading from the input stream I get a "java.net.SocketException: Socket closed" exception.
    Is there a way to send an EOF signal in the output stream? Am I doing something wrong?
            Socket sock = new Socket(this.getHost(), this.getPort());
            DataOutputStream os = new DataOutputStream(sock.getOutputStream());       
            DataInputStream is = new DataInputStream(sock.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String responseString = new String();
            if (sock != null && os != null && is != null) {
                os.writeBytes(request);
                String responseLine;
                while ((responseLine = reader.readLine()) != null) {
                    responseString += responseLine;
            } //endif
            os.close();
            is.close();
            sock.close();

    Thanks for the reply. Is there no way around that? I don't have direct control over the server.
    I don't understand why I can't close the socket's input stream and still read from its output stream.
    Edited by: philgmo on Feb 18, 2008 3:20 PM

  • Sockets: How do I know how much I can read from a socket?

    Hi everyone,
    I've opened a socket connection to a cisco router and want to read some of its databases. These are the main part of my code:
    Socket so = new Socket(routerIP, routerPort);
    BufferedReader br = new BufferedReader(
    new InputStreamReader(so.getInputStream()));
    BufferedWriter bw = new BufferedWriter(
    new OutputStreamWriter(so.getOutputStream()));
    // user/password entered.
    bw.write("show ip alias\r\n");
    bw.flush();
    while ((in = br.readLine()) != null) {
    System.out.println(in);
    so.close();
    The problem occurs in the "while" loop at the end of the code. The last line that the router is sending doesn't have a \r\n at the end and therefore my readLine command waits indefinitly.
    Well, I guess I can change that command with a simple read but still it won't be general. I'm looking for a command like "available" in socketImpl that tells me the number of bytes that I can read from the server beforehand.
    Any solutions?????????????
    Thanks,
    Ali.

    Ok, that much I know from the router. It supports
    telnet. So, basically if a telnet client can tell when
    it has read all the data coming from the router and
    when it has to wait for user to input the data, I have
    to be able to do so too.Hi, telnet does not know that it has read all the data coming from the router or from you; It waits for data from both sources (the router and you), and then retransmits that data to (you or the router respectively.)
    telnet must be sending and receiving data byte by byte
    cause what we type is displayed on the screen if the
    server echos the characters back to the client.
    Any suggestions, anyone knows of a simple telnet
    source?True. In particular, telnet does not care whether there is any carriage return or linefeed characters. It just retransmits whatever it gets from the source to the destination, except that it looks for particular escape sequences from the data source, such as the sequence for shutting out echo when you enter passwords.
    In your case, I am not sure what you want to achieve. I think you are trying to find the end-of-data but the end-of-data is not unambiguously terminated by an end-of-line. Maybe you need to find some other character or even strings for that purpose. You may even need to process the whole data received in order to determine the end of it.
    However, if you just want just that answer from the router and no more, you can send your logout after your query, so that after the router replies your queries, it also closes the connection and your BufferedReader.readLine() will return.

  • Parsing XML from a socket that does not close

    Hi -
    I've seen similar questions to this already posted, but either they did not really apply to my situation or they were not answered.
    I have to read messages from a server and process them individually, but the protocol does not indicate the message length or give any sort of terminating character. You only know you have a complete message because it will be a well formed XML fragment. To complicate matters more, there could be extra binary data preceding each XML message. I must stress that I did not write this server, and I have no influence over the protocol at all, so while I certainly agree that this is not such a good protocol, changing it is not an option.
    I'm hoping that there is a reasonable way to deal with this with an existing parser. Ironically, I don't really need to parse the XML at all, I just need to know when the current message is over but the only indication I get is that it will be the end of an XML fragment.
    I do have the ability to strip off the non-XML binary data, so if there is some way that I can give the stream to a SAX (or other) parser when I know XML is coming and have it inform me when tags begin and end, or ideally inform me when it is done a complete XML fragment, that would be perfect. I'm aware of how to do this using SAX normally, but it seems that it will not function correctly when there is no EOF or other indication that the document has ended.
    The best algorithm I have come up with (and it's pretty cheesy) is:
    1. Start with a string buffer.
    2. Append data from the socket to the buffer one byte at a time.
    3. Keep checking if there is a '<' character that is not followed by '?' or '!'. (ie - don't concern myself with the special XML elements that don't close with '/>' or </tagName>. I keep them in the buffer to pass on when I'm done though.)
    4. When I get my first tag with <tagName> I make note of what this tag is and increment a counter. If the tag is self closing, then I'm done.
    5. Anytime I see this tag I increment the counter.
    6. Anytime I see </tagName> I decrement the counter. If the counter = 0, I am done.
    7. I pass on the entire message, preceding binary data, special XML tags and the fragment to the module that actually processes it.
    This has a few problems. I'll have to go out of my way to support multiple character encodings, I'll have to be careful to catch all the special XML tags, and its quite CPU intensive to be interested in every single character that comes down the pipe (but I suppose this is not avoidable). Also, I just don't like to re-invent the wheel because I'm likely to make an error that a well established parser would not make.
    Does anyone have any suggestions for this, or know of a parser that will deal with fragments using streams that don't close?
    Thanks!

    The parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.

  • Reading/Writing Multiple Files From/To Socket

    I'm have a problem in recognizing end of file in socket.
    when I write files one after another using object input stream wrapped on the socket's input stream.
    on one side:
    while((n = send_file_input_stream[ i ].read(buff)!=-1)
    socket_output_stream.write(buff,0,n)
    on the other side:
    while((n = socket_input_stream.read(buff)!=-1)
    recv_file_output_stream[ i ].write(buff,0,n)
    this process happens for i=1..N files
    1) how can i signal the socket That EOF occures ?
    2) how can the recieving socket stream recognize it?
    3) Is there a simple mechnism for transffering files in java
    from dir to dir from disk to socket ?
    like copy(InputStream from,OutputStram to)
    Thanks
    Joseph

    one way is to write something as an end of file marker after each file, say character 255, just make sure you escape any 255's in the file (say by sending two 255's)
    The other end then needs to look for the 255's, if it gets one on its own its the end of the file. If it get's two together its a single 255 thats part of the file.
    If that seems a bit complicated you could send a header with the count of bytes before each file, the receiving end then just has to count bytes.
    Another way is to use a new connection for each file (probably also the easiest)

  • Getting parameters from text and file input tag. .  canyou help me ?

    Hello!
    Is there anyway of getting parameters from an
    text field input in a form like :
    <form name="signinForm" method="post" action="uploadFile.jsp" enctype="multipart/form-data" >Actually I would like to insert the parameters and make the upload of an file
    on the same form. It is something likethis :
    Form.jsp
    <form name="signinForm" method="post" action="uploadFile.jsp" enctype="multipart/form-data" >   
    <input type="text" id="name" name="signinName" />
    <input name="signinFile" id="fileUp" type="file" />   
    <input type="submit" id="submit_btn" name="signinSubmit"/>uploadingFile.jsp
    <%@ page import="java.io.*,javax.servlet.http.HttpServletRequest,javax.servlet.ServletInputStream" %>
    <%@ page import="java.io.FileWriter,java.io.IOException" %>
    <%
    .//upload the file
    String email = request.getParameter("signinName").trim(); //this line is bringing me an NullPointerException
    %>Thanks in advance for any suggestion!!
    All the best!

    You cannot use the HttpServletRequest object to retrieve parameters from a multipart form. You'll have to use a package that can parse such a form. I suggest Apache commons FileUpload.
    http://jakarta.apache.org/commons/fileupload/
    Using this package you can get both the file upload and any other parameters.

  • Reading int data from a socket

    Hi!
    I'm new here and I have a question. I'm reading bytes from a socket and I'm trying to get some integers from a byte array. But I have a problem. I'm able to read the byte array but i can't get correct int numbers from it. For example i have a byte array with following bytes:
    10004000-82-72-109-84
    When I read those int's with, for example DataInputStream.readInt() first two numbers i get are 16777216 and 67108864 but I know they should be 1 and 4. I know because this is what server sends and I get this reading data in some other languages for example C or even PHP. I even tried using ByteBuffer but with same wrong result. Maybe it has something to do with little/big endian or something, I don't know. Maybe somebody could tell me how to get correct numbers. Maybe I should do it other way than reading byte array... I have no idea... :(
    Thanks!

    If you cannot change the transmitting application,
    you'll have to compensate in your Java application
    by using ByteBuffer in backward-endian mode.Well... I cannot change the transmitting application. Simply, I have no acces to it. I tried with using ByteBuffer with LITTLE_ENDIAN order and it worked. Thanks!

  • Deleting a row from a Row Repeater

    Hi All,
    How could i delete a row from a row repeater??????
    I am using REMOVE_ELEMENT method from IF_WD_CONTEXT_NODE interface... Is this the correct way!!!!!!.
    Is there anyother way to do the same?????
    Best Regards.
    Shafiq Ahmed Khan.

    Hi
    first u get the index from the context element. with the help of the index u can get that particular element using get element.
    then u remove the element .
    check this code.
    CALL METHOD context_element->get_index
      receiving
        my_index = lv_index.
    CALL METHOD lo_nd_rcf_edu_det->get_element
      EXPORTING
        index        = lv_index
      receiving
        node_element = lo_el_rcf_edu_det .
    CALL METHOD lo_nd_rcf_edu_det->remove_element
      EXPORTING
        element          = lo_el_rcf_edu_det
    receiving
       has_been_removed =
    Declare a parameter context_element in the method of type if_wd_context_element
    regards
    chythanya

Maybe you are looking for