Object Output Stream - In Deepth

Previous Problem
- Was sending java.util.Set over ObjectOutputStream, however say the set had 4 objects in it the first tym sent, 4 objects would also be in it when recived at server side, but second tym the set was sent, say 2 of those objects were removed, there would be an output of 2 objects on the client side but still 4 on the server side.
- Answered Below by a member of the forums -
The object output stream deals with objects.
When you hand your Set object to the ObjectOutputStream, it politely hands it to the server.
When you hand the same Set object to the OOS it notices that it's seen it before, and merely sends a sharp note to the server saying "oh yes, we've seen this one before".
Which is intentional - it's so that these classes...
public class Foo1 {
Foo2 foo;
public class Foo2 {
Foo1 foo;
...don't end up getting serialised for ever as it bounced between serialising Foo1's copy of Foo2 and Foo2's copy of Foo1 and Foo1's copy of - and so on.
In order to cause the new (empty) contents of the Set to be sent to the server, you'll have to either send a suitable command string (literally "CLEAR" or something), and detect that - or just create a new empty set and send that - for example:
output.writeObject(strings.clone());
Hope that's of help.
Dave.
Haha ok now i have a similar problem again, the server now recieves the correct amount of objects in the Set, however when a bullet is updated and it sends the set again, it recives the first bullets values. For example;
4 Bullets are shot, 4 Bullets are added to the Set, 4 Bullets send to server which are sent to oposition. This is great working well, now however, the bullets are update position changed, send the set again, but x and y values changed on client side, but when recieved on server side are the values of the first instance of that bullet sent.
EG:
Client send set Bullet x = 7 y = 7
Server recives Bullet x = 7 y = 7
Client send set bullet after values in Bullets changes x = 9, y = 9
Server recieves Bullet x = 7 y = 7
See the problem?
Haha very similar to the first problem, just dont know how to get around it.
Thanks in advance Nick

Check the reset() method on ObjectOutputStream.
if you call reset() before sending an object I think
this does what you want.I have just written a simple example to illustrate this. It resets the OOS on 'even' sends and not on 'odd' sends. As expected, it never receives updated objects on 'odd' sends.
import java.net.*;
import java.io.*;
public class Test1
    static class Item implements Serializable
        private int index = 0;
        void inc()
            index++;
        public int getIndex()
            return index;
        public String toString()
            return Integer.toString(index);
    static public void main(String[] args)
        try
            final ServerSocket serverSocket = new ServerSocket(12345, 10);
            Thread runner = new Thread()
                public void run()
                    try
                        Socket connection = serverSocket.accept();
                        ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
                        while (true)
                            while (true)
                                try
                                    Object obj = ois.readObject();
                                    System.out.println("Received : " + obj);
                                catch (Exception e)
                                    System.out.println("Exception 1 = " + e);
                                    e.printStackTrace();
                    catch (Exception e)
                        System.out.println("Exception 2 = " + e);
                        e.printStackTrace();
            runner.setDaemon(true);
            runner.start();
            Socket s = new Socket("localhost", 12345);
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            Item item = new Item();
            for (int i = 0; i < 10; i++)
                if ((i & 1) == 0)
                    oos.reset();
                oos.writeObject(item);
                System.out.println("Sent : " + i);
                item.inc();
            serverSocket.close();
        catch (Exception e)
            e.printStackTrace();
}

Similar Messages

  • Sending defaultTableModel via object output stream

    Hello,
    The defaultTableModel is make me crazy!
    The problem is;
    I have one server and x client.
    When new client is connected to the server, server sends the new client list in defaultTableModel.
    But only the last client is receive the new list.
    All other clients defaultTableModel.getrowCount returns 0
    Here are the codes:
    http://www.adatoz.com/files/java/daServer.java
    http://www.adatoz.com/files/java/daClient.java
    http://www.adatoz.com/files/java/aaServerThread.java
    first run server :-)
    then clients..
    first client nick list is okay.
    but when the second client was come, first client list is zero..
    Thank you,

    When you send the DefaultTableModel, you have sent a copy. When you resend it send the refrence again, but not the values. Thus once you send a object in an ObjectStream sending it again will not update it.
    What you need to do is send a new Vector containing the new data.

  • Object input/output stream

    Hi, i'm currently doing a software enginnering project at university. I need to understand how to save and read from files.
    I've been told to look at object input/output stream, which I have, but I can't get my head around what's written in the books. Does anyone know where i can find a good tutorial on this subject?
    thanks
    AK

    I like the tutorial on this site because it tells you what to use for what you're doing (click on Using the Streams). Hope it helps!
    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Questions about input/output streams

    In the following tutorial:
    http://chortle.ccsu.ctstateu.edu/CS151/Notes/chap85/ch85_10.html
    It mentions that some methods, such as write(), writeByte(), writeBytes(), and writeChar(), return the low eight bits of the argument to the output stream. I am a little unsure of what exactly that means, might somebody be able to clarify for me?
    In addition, I've been encountering the flush() method in some of the byte- and character-streaming objects that deal with buffers. What exactly is the flush() method's purpose, and when might it be used? Thank you.

    flush pushes the data out of the buffer. the write methods write to the buffer, when the buffer is full, it flushes itself (usually), or it could block the write methods (in theory). flush just lets you make sure that it's flushed.
    I'm not sure there's any reason to worry about high and low bytes in Java most of the time. I suppose, like anything, there's times you need to, but I can't think of any offhand.

  • Facing error in creating ObjectInput/output stream socket

    hi I am Jatandar and i am implemeint client server program which will be using object Input/Output stream to pass data through sockets . The problem is the i m getting error when the cleint connects to the server here is the server and client code , YOur help will be appreciated
    Inventory class with serializable has been implemented
    public class Client
    public static void main( String [] args )//throws IOException
    Inventory invt[];
    try
    Socket serv = new Socket( "localhost", 8000 );
    // connect to server at port 8000
              ObjectInputStream ois ;     
    ois= new ObjectInputStream(serv.getInputStream());
    invt=(Inventory[]) ois.readObject() ;
    System.out.println(invt[0]);
    catch(IOException e )
    System.out.println(" no server Found \n");
    catch(Exception e)
    System.out.println(e);
    public class A3Server
         public static void main(String arg[] ) throws IOException
              //create a Server Socet
              ServerSocket ss= new ServerSocket(8000) ;
              ObjectOutputStream oos;
              //create a clent Socker that will listen for connection
              //listen for the connection from client
              BufferedReader br=null;
              FileReader fr=null;
              LinkedList ll=new LinkedList();
              StringTokenizer stkr;
              int i=0;
              Inventory inv=new Inventory();
              Inventory invt[];
              String t[]=new String[5];
              boolean choice=true;
              String temp="",temp2;
    // i am reading a text which contain data
    //that data is stored in invt []
    //that array is transfered to clien t when it is connected
         Socket toClient= ss.accept();
    oos = new ObjectOutputStream(toClient.getOutputStream());
    oos.writeObject(invt );
         oos.close();     
              }// end of main fucniton
         }//end of Server class
    DETAIL OF ERROR
    error in natived socket write method

    hi I am Jatandar and i am implemeint client server program which will be using object Input/Output stream to pass data through sockets . The problem is the i m getting error when the cleint connects to the server here is the server and client code , YOur help will be appreciated
    Inventory class with serializable has been implemented
    public class Client
    public static void main( String [] args )//throws IOException
    Inventory invt[];
    try
    Socket serv = new Socket( "localhost", 8000 );
    // connect to server at port 8000
              ObjectInputStream ois ;     
    ois= new ObjectInputStream(serv.getInputStream());
    invt=(Inventory[]) ois.readObject() ;
    System.out.println(invt[0]);
    catch(IOException e )
    System.out.println(" no server Found \n");
    catch(Exception e)
    System.out.println(e);
    public class A3Server
         public static void main(String arg[] ) throws IOException
              //create a Server Socet
              ServerSocket ss= new ServerSocket(8000) ;
              ObjectOutputStream oos;
              //create a clent Socker that will listen for connection
              //listen for the connection from client
              BufferedReader br=null;
              FileReader fr=null;
              LinkedList ll=new LinkedList();
              StringTokenizer stkr;
              int i=0;
              Inventory inv=new Inventory();
              Inventory invt[];
              String t[]=new String[5];
              boolean choice=true;
              String temp="",temp2;
    // i am reading a text which contain data
    //that data is stored in invt []
    //that array is transfered to clien t when it is connected
         Socket toClient= ss.accept();
    oos = new ObjectOutputStream(toClient.getOutputStream());
    oos.writeObject(invt );
         oos.close();     
              }// end of main fucniton
         }//end of Server class
    DETAIL OF ERROR
    error in natived socket write method

  • Output Stream to JTextArea

    Hi there,
    I would like to have the output stream coming from the server to the client displayed on a JTextArea. However, because the coming file is a text document that had its file name passed as a local variable in the main method header with String a[ ], I am having difficulty setting this as the area text because of the incompatible types. This text prints on my command prompt window but I cannot figure out how to get this stream into the JTextArea. This is my code. The objective is to ask a file from the server and have the server send this file to the client so the client can then make changes and save.
    import java.io.*;
    import java.net.*;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.Formatter;
    public class Client extends JFrame{
            public static JTextArea enterArea1;
            public static JTextArea enterArea2;
            public JButton change;
            public JButton save;
      public Client()
            super ("Client to Server");
            Box box = Box.createHorizontalBox();
            enterArea1 = new JTextArea(10, 15);
            enterArea1.setEditable (true);
            box.add (new JScrollPane (enterArea1));
            change = new JButton("Make Changes");
            box.add(change);
            change.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                Scanner console = new Scanner (System.in);
             System.out.print ("Input File: ");
             String inputFileName = console.next ();
             System.out.print ("Enter the text that you want to change");
             String inputText1 = console.next ();
             System.out.print ( "Output File: ");
             String outputFileName = console.next();
              try
              FileReader reader = new FileReader (inputFileName);
              Scanner in = new Scanner (reader);
              PrintWriter out = new PrintWriter (outputFileName);
                   String line1 = in.nextLine();
                   out.println( " " + inputText1 );
              out.close();
              catch (IOException exception)
              System.out.println ("Error processing file: " + exception);
            save = new JButton("Save to File");
            box.add(save);
            save.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                enterArea2.setText (enterArea1.getSelectedText());
            enterArea2 = new JTextArea (10, 15);
            enterArea2.setEditable (false);
            box.add (new JScrollPane (enterArea2));
            add (box);
      public static void main(String a[]) throws IOException {
            Socket sock;
            BufferedReader dis;
            PrintWriter dat;
            Client sendServer = new Client();
            sendServer.setSize (500, 200);
            sendServer.setVisible(true);
            sendServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            sock = new Socket("127.0.0.1",4444);
            dis = new BufferedReader( new InputStreamReader(sock.getInputStream()) );
            dat = new PrintWriter( sock.getOutputStream() );
            dat.println(a[0]);
            dat.flush();
            enterArea1.setText(a[0]);
            PrintStream os = new PrintStream (new FileOutputStream ("out.txt"));
            String fromServer = dis.readLine();
            while (fromServer != null )
               System.out.println(fromServer);
               os.println(fromServer);
               fromServer = dis.readLine();
            sock.close();
    }

    I believe that the logic is to append the text to the JTextArea with something along the lines of this, but since String a[0] is passed in my void method, it is not accepted as a string anymore. The question then becomes how to create a variable that is referenced to the output text on the command window so that this variable can be used to append the same text to the JTextArea. I will appreciate any comments. Right now, it sees the String text as null.
    String text = dat.println(a[0]);
                          dat.flush();
            enterArea1.append(text]);

  • Compress the output stream..

    Hello every body..
    I have aproject that use the java applet to transmit a vedio and audio over the internet network to do a video conference application with other applet at another computer at the network..
    I want to support the application so that the user that enter the conference can select the bandwidth of the internet he/she use and then accordin to choice i control the quality of the stream transmitted..
    So i want any one can help me with any way can be used to reduce the quality( or resolution) of the output stream so the user can be comfortable with the output..
    please any one can help me reply to me as fast as can..
    I there is no method can be used also reply and say this..
    Thanks...

    Hi,
    For audio use GSM codec. It just takes 12kbps of your bandwidth.
    For video, if you need "ok" quality with low bandwidth, use H.263 codec and for good quality, but higher bandwidth use JPEG codec. below are complete functions on how to reduce qualities for both codecs (or at least try to). But before you have to create a video Processor (see AVTransmit3.java and AVReceive3.java examples on the net).
    private void setReducedJPEGQuality(Processor videoProcessor) {
       Control cs[] = videoProcessor.getControls();
       QualityControl qc = null;
       VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
       // Loop through the controls to find the Quality control for
       // the JPEG encoder.
       for (int i = 0; i < cs.length; i++) {
          if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) {
             Object owner = ((Owned)cs).getOwner();
    // Check to see if the owner is a Codec.
    // Then check for the output format.
    if (owner instanceof Codec) {
    Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
    for (int j = 0; j < fmts.length; j++) {                    
    if (fmts[j].matches(jpegFmt)) {               
    qc = (QualityControl)cs[i];          
    qc.setQuality(0.5f);               
    break;
    if (qc != null) {
    break;
    This will reduce your JPEG bandwith to an average of 150kbps, with still a good quality.
               private void setReducedH263Quality(Processor videoProcessor) {
             Control cs[] = videoProcessor.getControls();
              QualityControl qc = null;
              BitRateControl brc = null;
              FrameRateControl frc = null;
              boolean done = false;
              //try with bit rate first
              for (int i = 0; i < cs.length; i++) {
                  if(cs[i] instanceof Owned) {
                      if(cs[i] instanceof BitRateControl) {
                           brc = (BitRateControl)cs;
                   if(brc.getBitRate()>0) {
                        brc.setBitRate(30000);               done = true;
                   brc = null;
              if(done) {
                   return ;
              //then look for quality control
              for (int i = 0; i < cs.length; i++) {
              if(cs[i] instanceof Owned) {
              if(cs[i] instanceof QualityControl) {
                   qc = (QualityControl)cs[i];
                   if(qc.getQuality()>0.0f) {
                        qc.setQuality(0.5f);
                        done = true;
                   qc = null;
              if(done) {
                   return ;
              //if that did not work, try setting frame rate
              for (int i = 0; i < cs.length; i++) {
              if(cs[i] instanceof Owned) {
              if(cs[i] instanceof FrameRateControl) {
                   frc = (FrameRateControl)cs[i];
                   frc.setFrameRate(6.0f);
                   frc = null;
    This will reduce your H.263 codec's bit rate to 80kbps. You cannot set less than that. I tried with many webcams and that's the least I could go.
    Good luck.

  • Oracle BLOB Writes the Bytes Twice to Output Stream

    Hi,
    I have a very strange problem when working with oracle.sql.BLOB; I cannot figure out what it's causing my BLOB stream output to double the amount of data inserted into the Oracle database. I have a table that contains two BLOB objects(image files) and the goal is to insert two images into each row by BLOB stream.
    For example, if the image_bin size is 800k and image_thumbnail size is 100k, this code actually writes 1600k (double) and 200k (double) the amount of bytes to each BLOB column, respectively. The print method in insertBlob() indicates a correct number of bytes being written to the output stream (800k and 100k).
    I know for the fact the retrieval method (not mentioned here) doesn't duplicate the bytes when it's read because I have written another test program that does not utilize oracle.sql.BLOB but instead uses PreparedStatement's setBinaryStream(index, InputStream, size_of_file) and it accurately writes the exact image size (no double sizing) to the database -- but not with BLOB. Here's a snippet of my code, note that the actual writing occurs in insertBlob():
    private void insertBlob(java.sql.Blob lobImage, String imgName)
    throws SQLException, IOException {
    File imgFile = null;
    FileInputStream imgOnDisk = null;
    OutputStream imgToDB = null;
    int bufferSize = 0;
    oracle.sql.BLOB blobImage = (oracle.sql.BLOB) lobImage;
    try {
    int bytesRead = 0;
    long bytesWritten = 0L;
    byte[] byteBuffer = null;
    bufferSize = blobImage.getBufferSize();
    byteBuffer = new byte[bufferSize];
    imgFile = new File(imgName);
    // Stream to read the file from the local disk
    imgOnDisk = new FileInputStream(imgFile);
    // Stream to write to the Oracle database
    imgToDB = blobImage.setBinaryStream(imgFile.length());
    // Read from the disk file and write to the database
    while ((bytesRead = imgOnDisk.read(byteBuffer)) != -1 ) {
    imgToDB.write(byteBuffer, 0, bytesRead);
    bytesWritten += bytesRead;
    } // end of while
    System.out.print("Done. " + bytesWritten + "-bytes inserted, buffer size: " +
    bufferSize + "-bytes, chunk size: " +
    blobImage.getChunkSize() + ".\n");
    } catch (SQLException sqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.processBlob()");
    connRollback();
    throw sqlEx;
    } catch (IOException ioe) {
    System.out.println("IOException caught: JDBCOracleLOBBinaryStream.processBlob()");
    throw ioe;
    } finally {
    try {
    if (imgOnDisk != null ) {
    imgOnDisk.close();
    if (imgToDB != null ) {
    imgToDB.close();
    } catch (IOException ioeClosing) {
    System.out.println("IOException caught: JDBCOracleLOBBinaryStream.processBlob() " +
    "on closing stream.");
    ioeClosing.printStackTrace();
    } // end of finally
    public void insertImageIntoOracleDB() throws SQLException, IOException {
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
    this.getConnection(_driver, host, port, database, user, _pass);
    pstmt = conn.prepareStatement("INSERT INTO " +
    " gallery_v (picture_id, picture_title, image_bin, image_thumbnail) " +
    " VALUES (?, ?, EMPTY_BLOB(), EMPTY_BLOB())");
    pstmt.setInt(1, picID);
    pstmt.setString(2, picTitle);
    pstmt.executeUpdate();
    stmt = conn.createStatement();
    rset = stmt.executeQuery("SELECT image_bin, image_thumbnail FROM gallery_v " +
    " WHERE picture_id = " + picID + " FOR UPDATE");
    int rsetCount = 0;
    oracle.sql.BLOB imgBlob = null;
    oracle.sql.BLOB imgThumbBlob = null;
    while (rset.next()) {
    imgBlob = ((OracleResultSet) rset).getBLOB("image_bin");
    System.out.print("Inserting " + img + "... ");
    insertBlob(imgBlob, img);
    imgThumbBlob = ((OracleResultSet) rset).getBLOB("image_thumbnail");
    System.out.print("Inserting " + imgThumb + "... ");
    insertBlob(imgThumbBlob, imgThumb);
    rsetCount++;
    System.out.println("\nNumber of rows updated: " + rsetCount);
    conn.commit();
    } catch (SQLException sqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.insertImageIntoOracleDB()");
    connRollback();
    throw sqlEx;
    } catch (IOException ioe) {
    throw ioe;
    } finally {
    try {
    if (rset != null) {
    rset.close();
    if (pstmt != null) {
    pstmt.close();
    if (stmt != null) {
    stmt.close();
    closeConnection();
    } catch (SQLException closingSqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.insertImageIntoOracleDB() " +
    "on closing ResultSet or PreparedStatement.");
    closingSqlEx.printStackTrace();
    } // end of finally
    }

    Make a lumpy mistake; the new BLOB#setBinaryStream() method takes a position of where the data is read from in the stream given to it. So the following code:
    imgToDB = blobImage.setBinaryStream(imgFile.length());
    Starts off from the end of the file. Now I don't understand how this position would result in the duplicated amount of bytes read from the binary file (an image here) to the output stream! The correct line should be:
    imgToDB = blobImage.setBinaryStream(0L);
    ARGH!!! Now everything works as it expected. I gotta read the API's more carefully as I was expecting the same semantic parameter as PreparedStatement#setBinaryStream() which takes the length of the stream as one of its parameters.

  • Writing to servlet output stream

    Hi All,
    I am writing to a servlet(imageservlet) output stream in a jsp page two times as follows:
    <img src="\imageservlet?key=x1">
    <img src="\imageservlet?key=x2">
    It is causing memory errors. Do I have to take special precautions?
    Thanks inadvance.

    Hi,
    THis is my servlet code.
    import java.io.*;
    import java.io.StringWriter;
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.awt.Color;
    import com.trizetto.healthweb.service.GenerateImage;
    * Simple servlet to use with Image I/O generator
    public class GenerateImageServlet extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
         String className="PieChartGenerator";
         if(request.getParameter("keyName").equals("Pie"))
              className=PieChartGenerator";
         else if( request.getParameter("keyName").equals("Gantt") )
              className="GanttChartGenerator";
    try
    GenerateImage ge=
    (GenerateImage) Class.forName(className).newInstance();
    String type = ge.createImage(response.getOutputStream());
    response.setContentType(type);
    catch (Exception e)
    throw new ServletException(e);
    But this one does not generate image. The image is generated from the Graphics object of the Frame.
    Something like the following code:
    http://www.javaworld.com/javaworld/jw-05-2000/servlets/Servlets.zip
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p2.html
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p1.html
    I am using Java 1.1.
    I am running my app. in websphere. The error happens randomly while I am stopping the websphere application server.
    Thanks in advance.

  • Do I need to study Inut/Output streams for the CX-310-035 exams

    Hi,
    I am a little confused.
    I have the Java 2 Certification Study Guid (Third Edition.
    In the objectives section, it says nothing of java.io (Input/OutPut streams right?), yet in the guide itself, it has a whole chapter on this.
    So what is the dea?Am I required to sudy this for the Sun Certified Programmer for the Java 2 Platform 1.4 (CX-310-035), or do I totally leave it out.
    Thanks all

    I find this to a bit stupid. I found reading the I/O chapter to be informative. I often did I/O things a bit blindly before preparing and am now better equipped to choose the correct classes when programming. Further, look how many questions we see in here of the ilk, "How do read from a file and then tokenize the bits and then do some processing and then write them back out using Unicode cuneiform"?

  • MultiThreading with Input and Output Streams

    Hi,
    I have a problem and I think it's because I'm not coding correctly. Please help me if you can understand what I'm doing wrong.
    I have a server that spawns a separate thread to go off and collect data from a serial port. It also waits to accept connections from any client and if a connection is made it will send that data to the clients connected.
    There is data constantly coming in through the serial port. It is output through a DataOutputStream so when the thread is created in the server, I pipe it into a DataInputStream. I do does because I want the server to then read in the data from the inputstream and then send it out to all my clients.
    So far, the way I have it set up seems to do this. But my problem occurs when I try to close a client connection. Instead of removing the socket connection it gives me an error that it can't send data to the client, but it shouldn't be sending data to the client because I just closed it. I realize this is probably because I'm still constantly receiving data from my inputstream and the connection was closed so it can't send that data to the client. I know I need to either close the stream or close my socket but I don't know where this needs to be done. I'm stuck on the correct way to fix this.
    My second problem is the initial connection made to receive data from the inputstream. This is probably because I'm not very familiar with how input/output streams work. But instead of just sending the client the current data being received in real time, it'll send all the data that's buffered in the inputstream. I don't want all the data that's been collecting to go to that first client. I only want the recent data that is coming through while the client is connected. Does this make sense? Because after I make a second client connection I don't have this problem because the InputStream is no longer buffered up. Should I be using something else besides the DataInputStream?
    I feel like I'm going about this the wrong way. Please advise. I'm shy about showing the code but I've included the bulk of it here in hopes that someone will see what I'm doing wrong. The only part that's left out is the thread that reads from the serial port. I don't seem to have any problems with that thread.
    Thanks,
    kim
    ===
    import java.io.*;
    import java.net.*;
    import javax.comm.*;
    import java.util.*;
    // DataServer waits for a client connection
    class DataServer
         static final int PORT = 7;
         // The ServerSocket to use for accepting new connections
         private ServerSocket ss;
         // A mapping from sockets to DataOutputStreams. This will
         // help us avoid from having to create a DataOutputStream each time
         // we want to write to a stream.
         private Hashtable outputStreams = new Hashtable();
         // The inputstream that will receive serial port data through a
         // piped inputstream
         public DataInputStream datalogger;
         // Constructor and while-accept loop all in one.
         public DataServer() throws IOException
              try {
                   // Creating pipe to convert the outputstream from the
                   // RS232 Thread to an inputstream for the server to read
                   PipedOutputStream pout = new PipedOutputStream();
                   PipedInputStream pin = new PipedInputStream(pout);
                   // The inputstream that will receive data from the RS232Thread
                   datalogger = new DataInputStream(pin);
                   // Spawn the thread that will read data through from
                   // the TINI serial port
                   new RS232Thread( pout ).start();
                   // Begin listening for connections and send data
                   listen();
              } catch (IOException ioe) {
                   System.out.println("Error >> DataServer::DataServer()");
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
              } finally {
                   try     {
                        System.out.println( "Closing >> DataServer::DataServer()" );
                        datalogger.close();
                   } catch (IOException i ) {
                        System.out.println( "Error2 >> DataServer::DataServer()" );
                        System.out.println(i); }
         private void listen() throws IOException
              // Create the ServerSocket
              ss = new ServerSocket( PORT );
              // Inform that the server is ready to go
              System.out.println( "Listening on " + ss );
              // Keep accepting connections forever
              while (true) {
                   // Grab the next incoming connection
                   Socket s = ss.accept();
                   // Inform that connection is made
                   System.out.println( "Connection from " + s );
                   // Create a DataOutputStream for writing data to the
                   // other side
                   DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
                   // Save this stream so we don't need to make it again
                   outputStreams.put( s, dout );
                   // Create a new thread for this connection, and then foret
                   // about it
                   new ServerThread( this, s );
         // Get an enumeration of all the OutputStreams, one for each client
         // connected to the server
         Enumeration getOutputStreams() {
              return outputStreams.elements();
         // Send a message to all clients (utility routine)
         void sendToAll( byte[] b ) {
              // synchronize on this because another thread might be
              // calling removeConnection() and this would screw things up
              // while it walks through the list
              synchronized( outputStreams ) {
                   // For each client...
                   for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
                        // ... get the output stream ...
                        DataOutputStream dout = (DataOutputStream)e.nextElement();
                        // ... and send the message
                        try {          
                             dout.write( b );
                        } catch(IOException ie) {                     
                             System.out.println( "Error >> ServerThread::sendToAll()" );
                             System.out.println( ie );
         // remove a socket, and it's corresponding output stream, from the
         // list. This is usually called by a connection thread that has
         // discovered that the connection to the client is dead.
         void removeConnection( Socket s ) {
              // Synchronize so it doesn't mess up sendToAll() while it walks
              // down the list of all output streams
              synchronized( outputStreams ) {
                   // Inform about removal
                   System.out.println( "Removing connection to " + s );
                   // Remove if from our hastable/list
                   outputStreams.remove( s );
                   // Make sure it's closed
                   try {
                        s.close();
                   } catch( IOException ie ) {
                        System.out.println( "Error closing " + s );
                        ie.printStackTrace();
         // main - Opens a server socket and spins off a new thread each time
         // a new client connection is accepted on this socket.
         public static void main(String[] args) throws Exception
              System.out.println("Starting DataServer version 1.0 ...");
              try     
                   new DataServer();
              catch (IOException ioe)
                   System.out.println( "Error >> DataServer::main()" );
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
    class ServerThread extends Thread
         //The Server that spawned this thread
         private DataServer server;
         // The Socket connected to the client
         private Socket socket;
         //Constructor
         public ServerThread( DataServer server, Socket socket )
              // save the parameters
              this.server = server;
              this.socket = socket;
              // Start up the thread
              start();
         // This runs in a separate thread when start() is called in the
         // constructor
         public void run() {
              try {
                   // The inputstream receiving data from the global inputstream
                   // that is piped to the RS232 Thread
                   // ???? is this where i'm messing up ???
                   DataInputStream in = new DataInputStream( server.datalogger );
                   int num = 0;
                   byte[] d = new byte[1];
                   // read from the inputstream over and over, forever ...
                   while( ( num = in.read(d) ) > 0 ) {
                        // ... and have the server send it to all clients
                        server.sendToAll( d );               
              } catch (IOException ioe) {
                   System.out.println( "Error >> ServerThread::run()" );
                   System.out.println(ioe.getMessage());
                   ioe.printStackTrace();
              } finally {
                   // The connection is closed for one reason or another,
                   // so have the server dealing with it
                   System.out.println( "Closing" );
                   server.removeConnection( socket );

    A couple of things to note...
    First, you are looping infinitely in your server's constructor. Since the constructor is never completing, your server object is never completely constructed - this may cause indeterminate behaviour when you pass a reference to the server to another thread.
    Second, I would recommend fixing your issues by modifying your design somewhat. The design I would recommend (read: The design I would use) is:
    A server object, with a public listen method. The constructor spawns a thread to constantly read from the serial port and forward the data read back to the server, via a multicast (sendToAll) method.
    The listen method sets up a server socket to accept connections, and in a loop opens client sockets and stores them in a set.
    The multicast method iterates through the list of open client sockets, and for each in turn confirms that it is still open. If open, send the data down the socket's output stream; if closed, remove the socket from the set.
    Note that this design includes only two threads - the main thread listens for and accepts new socket connections, while the extra thread collects data from the serial port, multicasts it to all of the open sockets, and removes all of the closed sockets. If you require to perform any other communication with the sockets, it may be necessary to create a thread for those sockets, to facilitate reading from their input streams, but in the given design, this is not necessary.
    I hope this helps,
    -Troy

  • Preventing servlet output stream to flush

    I increased the buffersize in the response object in order to make it possible for the entire jsp page to process before writing any output to the webclient.
    BUT since I use dynamic jsp-includes I fail to accomplish this, since according to the JSP1.3 specification the output stream is flushed before processing a dynamic include instruction.
    Is there a way I can make JSP to process the include and write output to buffer WITHOUT flushing it?
    Regards, Jon

    No I am using JSP 1.3. And I want to do the following:<%
    for (int i = 0; i < 5; i++) {
       // include("file_"+ i +".jsp");
    %>This to include file_0.jsp up to file_4.jsp.
    I assume the <jsp:include>tag is preprocessed hence only included once.

  • Opening Output Stream to a file on the server from Applet

    Hi,
    I am trying to write a little applet which parses a file found on the server , lets the user select some Strings then write the selected Strings to a different file on the server. I use the following code:
    String fileName = new String("LineUp");
    URL docBase = null;
    URLConnection conn = null;
    try {
    docBase = new URL(ApppletName.codeBase, fileName);
    } catch (java.net.MalformedURLException e) {
    System.out.println("Couldn't create image: "
    + "badly specified URL");
    try {
    conn = docBase.openConnection();
    } catch(IOException e) {System.out.println(e);}
    String playerString;
    try {
    conn.setAllowUserInteraction(true);
    conn.setDoOutput(true);
    conn.connect();
    PrintWriter out = new PrintWriter(
    conn.getOutputStream());
    etc..
    The problem I am having is that the getOutputStream routine for the connection object does nothing other than throw an exception (I've stepped through the code and that is all the routine actually does). The connection is actually made but no output stream can be created. I have looked at the Java Tutorial (as I am fairly new to Java) and found a spot where they tell you how to write to a file on the server, which is the example I have followed. Any suggestions? What am I missing?

    Yes, that's what I thought. It talks about writing to a URL, and you have interpreted "URL" as if it meant "file". A URL is a "Uniform Resource Locator", which is a string that identifies a "resource" on the server. Often that corresponds to a file on the server, but not always. It could be a page that is dynamically generated by a script on the server.
    Look again at that page and you will see these words: "At the other end, a cgi-bin script (usually) on the server receives the data, processes it, and then sends you a response, usually in the form of a new HTML page." What that means is, you can't just upload a file to a URL unless you have programmed the server to deal with that upload. That's part of the basic design of the HTTP protocol.
    So, unfortunately, you can't do what you want all that easily. You would have to provide some programming at the server to handle the file upload for you. In Java that means writing a servlet and getting the web server to have that servlet handle all requests to a particular URL. I suspect you don't want to get into that just yet. But if you do, any decent book on Java servlets should have an example of how to upload files like this.

  • Reading native process standard output stream with ProcessBuilder

    Hi,
    I'd like to launch an native process (windows application) which writes on standard output during its running.
    I'd like to view my application output on a JTextArea on my Java frame (Swing). But I do get all process output
    on text area only when the process is finished (it takes about 20 seconds to complete). My external process is
    launched by using a ProcessBuilder object.
    Here is my code snippet with overridden doInBackground() and process() methods of ProcessBuilder class:
    @Override
    public String doInBackground() {
    jbUpgrade.setEnabled(false);
    ProcessBuilder pb = new ProcessBuilder();
    paramFileName = jtfParameter.getText();
    command = "upgrade";
    try {
    if (!(paramFileName.equals(""))) {
    pb.command(command, jtfRBF.getText(), jtfBaseAddress.getText(), "-param", paramFileName);
    } else {
    pb.command(command, jtfRBF.getText(), jtfBaseAddress.getText());
    pb.directory(new File("."));
    pb.redirectErrorStream(false);
    p = pb.start();
    try {
    InputStream is = p.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    jtaOutput.setText("");
    while ((line = br.readLine()) != null) {
    publish(line);
    } catch (IOException ex) {
    Logger.getLogger(CVUpgradeFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(CVUpgradeFrame.class.getName()).log(Level.SEVERE, null, ex);
    jtaOutput.setText("");
    jtaOutput.setLineWrap(true);
    jtaOutput.append("Cannot execute requested commmad:\n" + pb.command());
    jtaOutput.append("\n");
    jtaOutput.setLineWrap(false);
    return "done";
    @Override
    protected void process(List<String> line) {
    jtaOutput.setLineWrap(true);
    Iterator<String> it = line.iterator();
    while (it.hasNext()) {
    jtaOutput.append(it.next() + newline);
    jtaOutput.repaint();
    //Make sure the new text is visible, even if there
    //was a selection in the text area.
    jtaOutput.setCaretPosition(jtaOutput.getDocument().getLength());
    How can I get my process output stream updated while it is running and not only when finished?
    Thanks,
    jluke

    1) Read the 4 sections of http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html and implement the recommendations. Although it is concerned with Runtime.exec() the recommendations still apply to Process generated by ProcessBuilder.
    2) Read about concurrency in Swing - http://java.sun.com/docs/books/tutorial/uiswing/concurrency/ .
    3) Use SwingUtilities.invokeLater() to update your GUI.

  • Sending Data Through a Output Stream...

    Hello,
    I am writing a program that works on a network...a server is running and client will connect to the server and send specific data for the server to complete transactions on.
    The transactions that are mainly seen are SQL SELECT statements and as you can imagine a statement could bring back many records.
    At present I have been able to send specific data through streams and have turned this into parameters on the server side and performed SQL. What I need help with or suggestions on is how to get the data back to the client. In some cases it may need to be displayed on screen or just used for further processing?
    Please let me know if this is not 100% clear.
    Thanks,
    P

    If you are able to send data over a network, then I assume that you know how to do network programming in Java, as well as knowing SQL.
    Java has JDBC - Java DataBase Connectivity API that supports your requirements in full.
    If you require a custom solution, then you need to be able to read data back from the server - when the server returns the ResultSet back to the client.
    A Socket object has both input and output streams. Seems that you know about the output stream, do you not know about the input stream?
    If the server is setup to send data back to the client over the same socket, then you should simply be able to read the results back from the socket's input stream.

Maybe you are looking for

  • Battery issues  done all suggestion

    I have just purchased a used 15" powerbook Aluminum 1.67. The PB works fine plugged in. When I unplug it, it shuts down within 5 minutes on battery power(it reads 100% charge). It won't star up on battery power you can hear the start up chime but it

  • Advice sought on external hard drives

    Could somebody please suggest a good quality external hard drive to use with a Mac PowerBook G4, which would be compatible with OSX 10.3.9 and 10.5 (which I will be installing shortly)? Thanks!

  • Servlet filter like functionality in WLS 5.1

    We have a requirement to be able to:           1) monitor incoming servlet requests and do processing dependant on the           parameter values in the http request           2) monitor outgoing servlet responses and when we certain strings redirect

  • Shadowy line and corners at bottom of display

    Hi all. I'm on my second MBP (late 2008) now because I took the first one back for having shadowy bottom corners on the display. Unfortunately the replacement has the same issue. The displays I've seen on in store models do not have the shadowy corne

  • ATV (3rd Gen 1080p) + Netflix website syncing issues?

    Hey there! I recently bought and started using a 1080p Apple TV. One of its main uses is going to be watching things such as Netflix. As great as the quality is and everything, even after watching something beginning to end (credits too), the netflix