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.

Similar Messages

  • 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();
    }

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

  • Sending Mail Via Invoice Output

    Dear Friends,
    We have a requirement of sending invoice data in excel, which has to be sent via invoice output, soon as we save the invoice. (like we fire print output or IDOC).
    We have written an ABAP program which generates such an excel file. Addtionally we have tried multiple options using Transmission medium like "Simple Mail" & "External Send", but in vain.
    It seems the standard functionality support sending the data in PDF format which we are able to do. But our requirement is it should be sent as an attachment in excel.
    Please help.
    Regards,
    Dhananjay

    Hi Dhanajya,
    http://wiki.sdn.sap.com/wiki/display/sandbox/ConversionofSpoolRequestDataintoPDFandExcelFormatandSenditintoMail. Given by MANSI ASNANI.
    Regards,
    Madhu.

  • Memory leak via object input stream (yes I'm resetting)

    I am seeing that my system is piling up char[] (according to netbeans profiler tool). I am running JDK 1.5 on linux, the client and server code look like this. The strings are piling up on the client side only. the allocation tree looks like this:
    char[]
    java.lang.String.<init>
    java.lang.StringBuffer.toString()
    java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(long)
    java.io.ObjectInputStream.readString(boolean)
    all the way to my client side code for receiving messages.
    Does anyone have any suggestions for something I'm missing?
    Client side code for receiving messages:
                TaskMessage tm = null;
                  try
                       ServerProcessor.debugPrint( "waiting on message from server" );
                       try
                            tm = ( TaskMessage ) fromServer.readObject();
                       catch ( ClassNotFoundException cnfe )
                            System.out.println( "Class not found exception while reading from server" );
                  catch ( IOException e )
                       System.out.println( "failed to make connection with server, disconnecting" );
                       m_connector.getProcessor().disconnect();
                       // kill the thread
                       isFinished = true;
                  catch ( Exception e )
                       System.err.println( "Caught exception while reading message from server.\nAssuming disconnect, attempting to reconnect" );
                       fromServer = m_connector.reconnect();
                       m_connector.getProcessor().disconnect();
                       isFinished = true;
                  // if we have a message then dispatch it
                  if ( tm != null )
                       ServerProcessor.debugPrint( "got non-null message from server" );
                       m_connector.serverMessageReceived( tm );
                  }Client side code for senting messages:
        public void sendServerMessage( TaskMessage tm )
             try
                  ServerProcessor.debugPrint( "Sending message back to server" );
                  m_out.writeObject( tm );
                  m_out.flush();
                  m_out.reset();
                  ServerProcessor.debugPrint( "Sent back to server at: " + System.currentTimeMillis() );
             catch ( IOException ioe )
                  System.out.println( "Unable to communicate with server." );
                  ioe.printStackTrace();
             catch ( Exception e )
                  // catch this silently... hopefully to avoid the broken pipe error display ( we handle it... just elsewhere )
             if ( tm.getType() != m_lastMessageType )
                  m_lastMessageType = tm.getType();
                  Runtime.getRuntime().gc();
                  System.out.println( "Remaining memory on client at the start of type " + tm.getType() + ": " + Runtime.getRuntime().freeMemory() );
        }Server Side Code for sending messages:
                                 try
                                      out.writeObject( m );
                                      out.flush();
                                      out.reset();
                                 catch ( Exception ioe )
                                      droppedClient();
                                 }Server side code for receiving messages:
                           // read the message
                            TaskMessage m = null;
                            try
                                 // will block here trying to read the clients reply
                                 m = ( TaskMessage ) in.readObject();
                                 ServerProcessor.debugPrint( "Received message at: " + System.currentTimeMillis() );
                                 ServerProcessor.debugPrint( "got client response" );
                            catch ( ClassNotFoundException cnfe )
                                 System.out.println( "Unable to locate TaskMessage Class" );
                                 cnfe.printStackTrace();
                            }

    I do have another memory leak in the system, what I am trying to determine from this post is if the way I am using read and write object may be contributing to that leak. I was hoping someone would be able to look at the communication code and let me know if I'm properly reseting the streams. Then at the very least I can rule this code out as the problem location and continue tracing the use of the read strings throughout the code.

  • Is there a general purpose output stream class like in java?

    Hi, I sometimes create tools (abap OO classes) which output characters, that I would like to store in any media (frontend file, server file, string variable, ftp, clipboard, etc.) This is easily done in java via the output stream classes.
    Do you know if this kind of class exists? I saw some classes like that, but they are specialized, for example XML, SOAP. I look for non-specialized classes like in java.
    Same question for input streams! (normally, we should deduct the input stream classes from the output stream classes)
    Or did you develop yourself such input stream or output stream classes that you'd accept to share?
    Thx a lot
    sandra
    Thx a lot!
    Edited by: Matt on Nov 20, 2008 9:50 AM - Fixed the posting

    Yes it exists, but in release 7.10 only. [ABAP Keyword Documentation u2192  ABAP - By Theme u2192  Process External Data u2192  Streaming|http://help.sap.com/abapdocu/en/ABENSTREAMING.htm]

  • To convert Smart Form output to PDF format and send it via email.

    Hi Friends,
    Could any one please tell me, how to convert the Smart Forms output to PDF format and send it via email to customer. If any one have the code, kindly mail me to [email protected]
    Thanks & Regards,
    John

    Refer the links -
    how to convert smartform into pdf and send through mail
    Smartform as PDF attachment to a mail.
    smartform pdf and mail
    smartform to pdf to mail
    Regrads,
    Amit
    Reward all helpful replies.

  • I have to send the sales order output via mail to a customer

    have to send the sales order output via mail to a customer, what steps i have to follow
    kindly guide me.
    regards
    satya

    Hello,
    You need to carru out your output configuration for this.
    Use tcode, NACE where you can do this centrally.
    Select V1 & click on output types above
    Select output type MAIL for your requirement & use tranmission medium as simple mail.
    After configuring your MP mail partner functions & use of proper output program you will be able to send mail to your party.
    Hope this is helpful to you.
    Regards,
    Dhananjay

  • To convert Sap Script output to PDF format and send it via email.

    Hi Friends,
    Could any one please tell me, how to convert the Sap Script output to PDF format and send it via email. If any one have the code, kindly mail me to [email protected]
    Thanks & Regards,
    John

    Plese check this sample code from other thread.
    REPORT zzz_jaytest .
    Types Declaration
    TYPES : BEGIN OF ty_pa0001,
    pernr TYPE pa0001-pernr,
    bukrs TYPE pa0001-bukrs,
    werks TYPE pa0001-werks,
    END OF ty_pa0001.
    Internal Table Declaration
    DATA : i_pa0001 TYPE STANDARD TABLE OF ty_pa0001, "For pa0001 Details
    i_otf TYPE STANDARD TABLE OF itcoo, "For OTF data
    i_content_txt TYPE soli_tab, "Content
    i_content_bin TYPE solix_tab, "Content
    i_objhead TYPE soli_tab,
    Work Area Declaration
    w_pa0001 TYPE ty_pa0001, "For pa0001 Details
    w_res TYPE itcpp, "SAPscript output
    "parameters
    w_otf TYPE itcoo, "For OTF
    w_pdf TYPE solisti1, "For PDF
    w_transfer_bin TYPE sx_boolean, "Content
    w_options TYPE itcpo, "SAPscript output
    "interface
    Variable Declaration
    v_len_in TYPE so_obj_len,
    v_size TYPE i.
    Constants Declaration
    CONSTANTS : c_x TYPE c VALUE 'X', "X
    c_locl(4) TYPE c VALUE 'LOCL', "Local Printer
    c_otf TYPE sx_format VALUE 'OTF', "OTF
    c_pdf TYPE sx_format VALUE 'PDF', "PDF
    c_printer TYPE sx_devtype VALUE 'PRINTER', "PRINTER
    c_bin TYPE char10 VALUE 'BIN', "BIN
    c_name TYPE string VALUE 'C:\ZZZ_JAYTEST.PDF',"Downloading
    "File Name
    c_form(11) TYPE c VALUE 'ZZZ_JAYTEST'. "Form Name
    START-OF-SELECTION.
    Selecting the records from pa0001
    SELECT pernr bukrs werks FROM pa0001
    INTO TABLE i_pa0001 UP TO 10 ROWS.
    Setting the options
    w_options-tdcopies = 1 ."Number of copies
    w_options-tdnoprev = c_x."No print preview
    w_options-tdgetotf = c_x."Return of OTF table
    w_options-tddest = c_locl."Spool: Output device
    Opening the form
    CALL FUNCTION 'OPEN_FORM'
    EXPORTING
    form = c_form
    device = c_printer
    language = sy-langu
    OPTIONS = w_options
    IMPORTING
    RESULT = w_res.
    LOOP AT i_pa0001 INTO w_pa0001.
    Writting into the form
    CALL FUNCTION 'WRITE_FORM'
    EXPORTING
    element = 'MAIN'
    window = 'MAIN'.
    ENDLOOP.
    Closing the form
    CALL FUNCTION 'CLOSE_FORM'
    IMPORTING
    RESULT = w_res
    TABLES
    otfdata = i_otf
    EXCEPTIONS
    unopened = 1
    bad_pageformat_for_print = 2
    send_error = 3
    spool_error = 4
    codepage = 5
    OTHERS = 6.
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    Converting OTF data to single line
    LOOP AT i_otf INTO w_otf.
    CONCATENATE w_otf-tdprintcom w_otf-tdprintpar
    INTO w_pdf.
    APPEND w_pdf TO i_content_txt.
    ENDLOOP.
    Converting to PDF Format
    CALL FUNCTION 'SX_OBJECT_CONVERT_OTF_PDF'
    EXPORTING
    format_src = c_otf
    format_dst = c_pdf
    devtype = c_printer
    CHANGING
    transfer_bin = w_transfer_bin
    content_txt = i_content_txt
    content_bin = i_content_bin
    objhead = i_objhead
    len = v_len_in
    EXCEPTIONS
    err_conv_failed = 1
    OTHERS = 2.
    v_size = v_len_in.
    Downloading the PDF File
    CALL FUNCTION 'GUI_DOWNLOAD'
    EXPORTING
    bin_filesize = v_size
    filename = c_name
    filetype = c_bin
    TABLES
    data_tab = i_content_bin.
    The extension is put the it_mailpack-obj_name parameter of 'SO_NEW_DOCUMENT_ATT_SEND_API1'.

  • Sending a Socket Object via a Socket :P

    eek Sorry all! I accidentally posted in "Java Programming" 1st... I don't know how to delete my post
    http://forum.java.sun.com/thread.jspa?threadID=5261765&tstart=0

    why ?
    At server side you can use input and output streams for communication.
    for example:
    You can have hashmap at serverside and put resp. sockets in it w.r.t. loginid.
    So you have
    key - socket
    loginA - SocketA
    loginB - SocketB
    now write "serialized" message class
    class Message implements Serializable {
    String from,to,message;
    // getter and setters for all
    put this class at client and serverside.
    When B will writeObject(message) to A he will actually writeObject(message) to server.
    Server will use getTo() method of class message.
    Server will get Socket from hashmap using getTo() "key" and will writeObject(message) To A
    Bye the way I am still curious why you want to send socket ?

  • Sending an InetAddress-object via udp

    hi there!
    i'm developing a videostream server/client application. client is an applet. what i want to do is this:
    since an applet has to be signed in order to perform dns-lookups, i want to work around that.
    since the applet has to request the stream anyway and therefore connects the server sending udp-
    packets, my idea was to let the server send back the clients IP/hostname as an InetAddress-object
    inside a udp packet.
    i tried the following:
    info: byte[] buf = new byte[256];
    on server:
    InetAddress address = packet.getAddress();
    buf = address.getAddress();
    packet = new DatagramPacket(buf, buf.length, address, port);
    socket.send(packet);
    on client:
    socket.receive(packet);
    byte[] temp = packet.getData();
    source = InetAddress.getByAddress(temp);
    System.out.println(source.toString());
    the system.out returns this: &#305;�A)
    or other unreadable stuff, depending on the ip-address of the client.
    i think, this has something to do with the conversion to/from bytearray, doesn't it?
    can anyone show me how to send an InetAddress-object so that i get an
    InetAddress-object out at the client side?
    thanks in advance!
    you can earn some bucks, too!
    greets
    honfrek

    hi there!
    thanks for your help. i got it figured out now.
    now it works like this:
    on server:
    InetAddress address = packet.getAddress();
    buf = address.getAddress();
    byte[] newbuf = new byte[buf.length];
    newbuf = buf;
    packet = new DatagramPacket(newbuf, newbuf.length, address, port);
    socket.send(packet);
    on client:
    byte[] newbuf = new byte[4];
    packet = new DatagramPacket(newbuf,newbuf.length);
    socket.receive(packet);
    source = InetAddress.getByAddress(packet.getData());
    i made 2 mistakes:
    - i converted the InetAddress to a string
    - the length of the byte[] was too big. i had a bunch of zeroes at the end

  • 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

  • How to send a Connection Object via CORBA

    Hi.
    I've got a question.
    How can I send a java.sql.Connection object
    using CORBA to a client? Tried to use a class
    MyConnection extending org.omg.CORBA.portable.ObjectImpl
    as a wrapper class. Didn't work.
    When a request was invoked for a Connection,
    no object was send. On client side an error occured:
    code 202 completed:maybe.
    In the IDL we used:
         typedef Object MyConnection;
         interface ConnectionPool{
              MyConnection getCon();
              void freeCon(inout MyConnection c);
    We were suggested to use structures. But ain't it
    inventing java again?
    Can anyone help us?
    Thx anyway.

    Try inserting it into an Any object and sending the any object over the IDL, the client can then extract the connection object.
    You might have to typedef the Connection object in the IDL to generate the helper class.
    /P/

  • 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

  • Getting the Output Stream of  a Process without exec()ing it first.

    Hi there,
    I am writing a java application which needs to open another application "gnuplot". Now my operating system is windows and I open pgnuplot .
    Also I want to send input to the above gnuplot (say plot sin(x) ) via the outputStream. The following is what I do :-
         String gnuplot_cmd = "plot sin(x)\n" ;
              Process p = Runtime.getRuntime().exec("C:/gnuplot/gnuplot4/bin/pgnuplot.exe");
              PrintWriter gp = new PrintWriter(p.getOutputStream());
              gp.print(gnuplot_cmd);
              gp.close();
    But the above doesn't work fully , in that only the blank wgnuplot terminal window pops up however I am unable to direct input to the gnuplot application.
    The reason being that , pgnuplot checks for
    its stdin being redirected the moment it's started. If, at that time,
    the "PrintWriter" is not yet connected to the OutputStream of the
    process, that check will fail, and pgnuplot will revert to just executing
    wgnuplot, without any command line redirection.
    I am facing a problem of how to attach a OutputStream to the process, without getting exec()ing the process.
    Is there anyway at all, i can get a process without starting it, so that I can attach an output Stream to it before it gets executed?
    I am open to work arounds, anything that will automate the process of writing to the gnuplot terminal.
    thanks!
    nandita.

    The reason being that , pgnuplot checks for
    its stdin being redirected the moment it's started.
    If, at that time,
    the "PrintWriter" is not yet connected to the
    OutputStream of the
    process, that check will fail, and pgnuplot will
    revert to just executing
    wgnuplot, without any command line redirection. I'm not convinced this analysis is correct. gnuplot doesn't need to know that there's a PrintWriter there, and it probably can't know. It just needs to know whether its standard input is coming from console or not. The Java library code that can invoke processes probably handles the redirect right away, and that's why there's the OutputStream available even before you create the PrintWriter.
    exec can be tricky. I think the problem may be that you're not dealing with standard output or standard error. Read this:
    When Runtime Exec Won't
    If that still doesn't help, there may be options to gnuplot to tell it exactly where its input is coming from.

Maybe you are looking for