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

Similar Messages

  • Problem trying to read an SSL server socket stream using readByte().

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Problems reading  an SSL server socket stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • How to read text from a web page

    I want to read text from a web page. Can any body tell me how to do it.

    Ok i tell you detail. visit the site " http://seriouswheels.com/" you will a index from A to Z which are basically car name index i want to read each page get car name and its model and store it in data base. I you can provide me the code i will be very thankful.

  • Is there a way to  have the iPad 2 "read" text from iBooks as with web sites or pages?

    is there a way to  have the iPad 2 "read" text from iBooks as with web sites or pages? A different App perhaps?

    Isn't that you asking how to get it (undefined) back?
    If you never had Pages '09, you can buy it from Amazon very cheaply:
    http://www.freeforum101.com/iworktipsntrick/viewtopic.php?t=432&sid=f68e84cd2ec6 123bd2ed93806c7e7fb6&mforum=iworktipsntrick
    Peter

  • How to read file from server

    Hi,
    When i try to read file from server,the following message is displayed .
    ORA-29532: Java call terminated by uncaught Java exception: java.security.AccessControlException: the Permission (java.io.FilePermission /tmp read) has not been granted to EWMTRACKTEST. The PL/SQL to grant this is dbms_java.grant_permission( 'EWMTRACKTEST', 'SYS:java.io.FilePermission', ' /tmp', 'read' )
    ORA-06512: at "EWMTRACKTEST.GET_DIRLIST_EWM", line 1
    ORA-06512: at line 1
    thanks and regards
    P Prakash

    it seems obvious, user EWMTRACKTEST doesn`t have access to directory /tmp and the file under that.
    try to give read permission and try again.
    you could use command line like 'chmod' to grant permissions.

  • Indesign CS3-JS - Problem in reading text from a text file

    Can anyone help me...
    I have an problem with reading text from an txt file. By "readln" methot I can read only the first line of the text, is there any method to read the consecutive lines from the text file.
    Currently I am using Indesign CS3 with Java Script (for PC).
    My Java Script is as follows........
    var myNewLinksFile = myFindFile("/Links/NewLinks.txt")
    var myNewLinks = File(myNewLinksFile);
    var a = myNewLinks.open("r", undefined, undefined);
    myLine = myNewLinks.readln();
    alert(myLine);
    function myFindFile(myFilePath){
    var myScriptFile = myGetScriptPath();
    var myScriptFile = File(myScriptFile);
    var myScriptFolder = myScriptFile.path;
    myFilePath = myScriptFolder + myFilePath;
    if(File(myFilePath).exists == false){
    //Display a dialog.
    myFilePath = File.openDialog("Choose the file containing your find/change list");
    return myFilePath;
    function myGetScriptPath(){
    try{
    myFile = app.activeScript;
    catch(myError){
    myFile = myError.fileName;
    return myFile;
    Thanks,
    Bharath Raja G

    Hi Bharath Raja G,
    If you want to use readln, you'll have to iterate. I don't see a for loop in your example, so you're not iterating. To see how it works, take a closer look at FindChangeByList.jsx--you'll see that that script iterates to read the text file line by line (until it reaches the end of the file).
    Thanks,
    Ole

  • Problem with reading text from .DOC files through java and POI

    I have used a jar file "poi-scratchpad-3.2-FINAL-20081019.jar" and "poi-3.2-FINAL.jar" to read text from a .DOC file. I used the "getParagraphText()" function of the class "org.apache.poi.hwpf.extractor.WordExtractor" to get the text.
    I am able to get the text in the .DOC file but along with that i am getting the following messages/warnings
    Current policy properties
    *     thread.thread_num_limited: true*
    *     file.write.state: disabled*
    *     net.connect_ex_dom_list:*
    *     mmc.sess_cab_act.block_unsigned: false*
    *     mmc.sess_cab_act.action: validate*
    *     mmc.sess_pe_act.block_blacklisted: false*
    *     mmc.sess_pe_act.block_invalid: true*
    *     jscan.sess_applet_act.stub_out_blocked_applet: true*
    *     file.destructive.in_list:*
    *     jscan.sess_applet_act.block_all: false*
    *     file.write.in_list:*
    *     file.nondestructive.in_list:*
    *     window.num_limited: true*
    *     file.read.state: disabled*
    *     jscan.session.origin_uri: http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/poi/poi/3.2-FINAL/poi-3.2-FINAL.jar*
    *     file.nondestructive.state: disabled*
    *     jscan.session.user_ipaddr: 10.136.64.153*
    *     net.connect_other: false*
    *     thread.thread_num_max: 8*
    *     file.destructive.ex_list:*
    *     file.nondestructive.ex_list:*
    *     file.write.ex_list:*
    *     jscan.sess_applet_act.sig_invalid: block*
    *     file.read.in_list:*
    *     mmc.sess_cab_act.block_invalid: true*
    *     jscan.session.policyname: TU1DIERlZmF1bHQgUG9saWN5*
    *     mmc.sess_pe_act.action: validate*
    *     thread.threadgroup_create: false*
    *     net.connect_in_dom_list:*
    *     net.bind_enable: false*
    *     jscan.sess_applet_act.sig_trusted: pass*
    *     jscan.session.user_name: 10.166.64.201*
    *     jscan.session.user_hostname:*
    *     file.read.ex_list:*
    *     jscan.sess_applet_act.sig_blacklisted: block*
    *     jscan.session.daemon_protocol: http*
    *     net.connect_src: true*
    *     jscan.sess_applet_act.unsigned: instrument*
    *     mmc.sess_pe_act.block_unsigned: false*
    *     file.destructive.state: disabled*
    *     mmc.sess_cab_act.block_blacklisted: true*
    *     window.num_max: 5*
    Below the above messages/warnings the data is getting printed. Only the text part of the data is retrieved not the fonts, styles and bullets etc.
    Can anyone explain me why I am getting above warnings and how can I remove them. Is it possible to fetch the text depending on delimiters.
    Thanks in advance,
    Tiijnar
    Edited by: tiijnar on May 21, 2009 2:45 AM

    The jar files which were used are downloaded from http://jarfinder.com. Those jars created the problem of displaying those messages on console. I downloaded APIs from apache.org and used them in my application. Now my application is running good.
    Tiijnar

  • Reading Texts from Infotype

    Hi,
    How can we read texts from the Infotype. There is this function module HR_ECM_READ_TEXT_INFOTYPE, but we need the Employee Number, Begin date and End Date as inputs.
    I just want to check if a field with a particular value exists or not.
    just like this works to check whether the field DAT35 with value 99991231 exits or not.
    SELECT PERNR FROM PA0035 INTO V_PERNR WHERE DAT35 = '99991231'.
    IF SY-SUBRC = 0.
    ENDIF.
    the same way for a text, but this text actually gets stored in a structure thats why we cannot use a select for infotype
    Thanks in advance.

    Hi,
    What i am getting from ur explanation is that u are having a probelm in accessing a text field from the infotype, i.e: the value field in included in the infotype table (PA0035) but its text is in another table.
    If this is the problem, u should first use select statement on PA0035 to get the required infotype record. Then use F1 help on the required text field on the infotype screen to get the table and field name. Then u can use select statement on that table by specifying the relavant value field from the previous select in the where clause.
    Hope this hepls

  • How do I read text from specific rows and columns in a tree structure?

    How do I read text from specific rows and columns in a tree structure? In a table you can specify the cell to read from but I have not been able to figure out how to do this with a tree structure.

    You need to set two properties to activate the correct cell and then you can read it's string property.
    The positioning properties are the "ActiveItemTag" and
    "ActiveColNum" properties. With them you select the tree item by it's tag and the active column. The string can then be read from the "Cell String" property.
    MTO

  • JavaConsole Error: Problem reading data from server

    HI All
    We are getting this error on java console on a page:
      Error: Problem reading data from Server - Java.Security.AccessControlException:access denied (java.util.PropertyPermission http.strictpostredirect Read)
    In this page we are not firing  a SQL Query of huge data.
    Any suggestions on this why it is happening?
    Thanks
    Manisha

    Manisha,
    I think JVM(Java Virtual Machine) is trying to access something at network level and it cant able to find it.Or any new patches of java is installed.
    Or may be due to IIS or Applet,Don't know exactly.
    You can find some answers in below links:
    http://java.sun.com/j2se/1.4.2/docs/api/java/security/AccessControlException.html
    http://www.webdeveloper.com/forum/archive/index.php/t-46358.html
    -Suresh

  • How to get server data without reading from the socket stream?

    My socket client checks for server messages through
                while (isRunning) { //listen for server events
                    try {
                            Object o = readObject(socket); //wait for server message
                                tellListeners(socket, o);
                    } catch (Exception e) {
                        System.err.println("ERROR SocketClient: "+e);
                        e.printStackTrace();
                    try { sleep(1000); } catch (InterruptedException ie) { /* ignore */ }
                }//next client connectionwith readObject() being
        public Object readObject(Socket socket) throws ClassNotFoundException, IOException {
            Object result = null;
    System.out.println("readObject("+socket+") ...");
            if (socket != null && socket.isConnected()) {
    //            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectInputStream ois = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
                try {
                    result = ois.readObject();
                } finally {
    //                socket.shutdownInput(); //closing of ois also closes socket!
        //            try { ois.close(); } catch (IOException ioe) { /* ignore */ }
            return result;
        }//readObject()Why does ois.readObject() block? I get problems with this as the main while loop (above) calls readObject() as it's the only way to get server messages. But if i want to implement a synchronous call in adition to this asynchronous architecture (call listeners), the readObject() call of the synchronous method comes to late as readObject() call of the main loop got called before and therefore also gets the result of the (later) synchronous call.
    I tried fideling around with some state variables, but that's ugly and probably not thread safe. I'm looking for another solution to check messages from the server without reading data from the stream. is this possible?

    A quick fix:
    - Add a response code at the beginning of each message returned from the server indicating if the message is a synchronous response or a callback (asynch);
    - Read all messages returned from the server in one thread and copy callback messages in a calback message queue and the synch responses in an synch responses queue;
    - Modify your synchronous invocation to retrieve the response from the responses queue instead from the socket. Read the callback messages from the corresponding queue instead from the socket.
    Also take a look at my website. I'm implementing an upgraded version of this idea.
    Catalin Merfu
    High Performance Java Networking
    http://www.accendia.com

  • Unable to read output from server on a socket

    Hello everyone,
    I am trying to re-develop and application that traditionally is developed in VB.
    Traditional program does following: communicates with host using telnet; login, send some text, read the output from server, validates output and terminated telnet connection.
    I am trying to build same kind of application in Java using sockets, but I do not get any response from the server.
    Any Suggestions ?
    Thanks,
    Code below:
    String hostName="ip address here";
    int portNum=23; //Verified that server's telnet runs on port 23
    try
    socket=new Socket(hostName,portNum);
    out=new PrintWriter(socket.getOutputStream(),true);
    in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }catch(UnknownHostException e){
    System.err.println ("Host not found: " + hostName);
    System.exit(1);
    }catch(IOException e){
    System.err.println("Could not get I/O for host: " + hostName + "on port: " + portNum);
    System.exit(1);
    BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    String userInput;
    try{
    while ((userInput=stdin.readLine()) != null)
    out.println(userInput);
    while (in.readLine() != null){
    System.out.println("echo: "+in.readLine()); // I Expect server's output here but nothing happens.
    }catch(IOException e){
    System.err.println("User Input not read.");

    while (in.readLine() != null){
    System.out.println("echo: "+in.readLine()); // I Expect server's output here but nothing happens.I see two problems here:
    1) in.readLine() only returns null if the socket is closed. You will be forever in that loop.
    2) you are losing every second line of your input. If your telnet server sends only one line at the beginning, the readline() call in the while statement will swollow that.
    If you want to do this in a single thread, you will have to use a method which won't block until input is available, such as the read(char[], int, int) method of BufferedReader.
    You could also use two threads, of which one is printing the output and the other is taking user input. This has the advantage, that you are able to handle any connection errors immediatley instead of only when the user entered a command.
    Does telnet send information about the end of an input sequence (like the end of the welcome message and the end of the answer to any issued command? If not, I'd say that you should use two threads, as you would have to do polling all the time otherwise.
    Hope it helps.

  • File transfer to multiple clients from server socket

    I have multiple clients connected to my server socket and I need to copy more than 200mb documents from server to all clients over socket. Can we design the issue considering scalability and performance factor? What I am thinking of we should use thread for transferring file from server to client. But at the same time if we have large number of clients then we can't initialize a thread for each client. I think in this case we should initialize less than 10 threads in the pool as the file size is very large. If we keep number of threads in the pool low then probably we have to read multiple times the large server file (once for each group) which might again be a performance bottleneck. Please pour in your suggestions.

    File would be same for an instance only. For example say I have a "SEND File" button & �File Path� text box. In File Path suppose user enters the absolute path of the file and then clicks on Send File button. The responsibility of Send File button would be sending the file mentioned in the "File Path" text box to all connected client. But next time user can choose a different file.

  • How to pre-allocate a ByteBuffer object to read data from a Socket

    Hi,
    So far every example on ByteBuffer allocation has shown something like this
    ByteBuffer buffer=ByteBuffer.allocate(1024);
    Im stuck because i dont know how much data will arrive on the socket. Is there anyway I can find out how much data is present on a socket before allocating the ByteBuffer? And if not, what can i do to ensure that I dont lose any of the data that is present on the socket and cant be read because the buffers limit may be too small.
    Thanks,
    Parth

    Hi,
    Bytebuffer is just buffer so make it big enough to handle traffic.. How big it must be depends on your applicaiotn and trasfered data amount..
    Following code shows an example which uses byte array as buffer... Following code is 1.2.x and above compatible using byte array instead ByteBuffer..
    Vector mainbuffer = new Vector(10,1);
    byte [] tempbuffer=new byte[5000]; // 5Kb buffer
    // STKInBufStr is bufferedinputstream to read data till end of stream ..
    // readcount show amount of data readed.. which means data amount in buffer. Data is written to buffer from start point -0,- 5000 is max read aomunt.
    // once read 5000 byte then it will return to while loop and create a temporary string and add it to manibuffer and menawhile coming data is not lost.. this loop will catch all incoming dta and buffer in mainfbuffer vector Roughly speaking bigger the buffer better te performance. Remeber code will wait to read 5000 byte of data to return to while loop. 5000 only means max amount of data it can handle in every read attempt.. if just read 2 byte it will return this 2 byte to loop
    while ( (readcount=STKInBufStr.read(tempbuffer,0,5000)) !=-1)
    String tmp = new String(readbuffer).substring(0,readcount);
    manibuffer.add(tmp);
    This loop will catch all incoming data and add to mainbuffer vector..

Maybe you are looking for

  • How do I get Flash player to Play

    I have watched a video on the web using flash in Firefox. I have saved the cache file of the video. I am now off line also the online video is no longer available from it's original source. Now I want to watch the video again using my saved Cache fil

  • Webutil error while generate excel form

    Hi In my forms appl. I use webutil in order to generate excel reports I have to midtier instances both running on a separate host. End users connect through a WLB frontend. At one of the midtiers, when generating a excel report using webutil "error w

  • URGENT -- Forms exit problem

    Hi, I am working with APS9i. I have forms in APS9i. I face problem when i call form b from form a. when i call for the first time form b opens and when i exit form b it comes back to form a but some times when i exit form b it closes all the previous

  • Keep together question

    Hi, I am using Crystal Reports XI R2 and I have a subreport in my details section. How can I keep the subreport from spanning to the next page? I need to keep it with the detail record it is associated with on the same page. Thanks Ron

  • Where are my mail attachments?

    Imac 10.4.7 mail does not show attachments; however, spotlight preview shows the attachments are with the email.