URGENT!! ObjectInput/Output stream

guys help me please,
i am writting a client/server application, and i want to send an object from the client to the server and send it back to the client. but see, when i run the program its gives
java.io.StreamCorruptedException:invalid stream header
my code is something like this:
BufferedReader br;
BufferedWriter bw;
ObjectOutputStream oos;
ObjectInputStream ois;
OutputStream ou;
InputStream iu;
Color color = JColorChooser.showDialog(
ClientGUIT.this, "Choose a color", color );
if ( color == null )
color = Color.LIGHT_GRAY;
try{
soc = new Socket( InetAddress.getByName( chatServer ), 1241);
br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
ou = soc.getOutputStream();
iu = soc.getInputStream();
oos = new ObjectOutputStream(ou);
ois = new ObjectInputStream(iu);
oos.writeObject(color);
oos.flush();
oos.close();
}catch(IOException e){addToTranscript("Error: " + e.toString());}
please can any one tell me how i can write this object into the socket without getting any exceptions.
Thanks in advance

ois = new ObjectInputStream(iu);The stream parameter in the constructor of the class ObjectInputStream should be the one that was written with ObjectOutputStream.

Similar Messages

  • 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

  • ObjectInput-Output Stream problem ?

    I have a server-client program and I am sending my data on OutputStream()
                input = new InputStream(mydataSocket.getInputStream()) ;
                output = new OutputStream(mydataSocket.getOutputStream()) ;
                objInput = new ObjectInputStream(input) ;
                objOutput = new ObjectOutputStream(output) ;but I am taking an error.
    Implement all abstract method() ;
    is this read() method necessary ?

    Server
        protected void runServer() throws IOException
            ServerSocket serSock = null ;
            Socket sock ;
            ObjectOutputStream output ;
            ObjectInputStream input ;
            String line ;
            ArrayList<String> al = new ArrayList<String>() ;
            try {
                serSock = new ServerSocket(5000,100) ;
                while (true)
                    sock = serSock.accept() ;
                    input = new ObjectInputStream(sock.getInputStream()) ;
                    output = new ObjectOutputStream(sock.getOutputStream()) ;
                        line = input.readUTF() ;
                        al.add(line) ;
                    try {
                            for ( int j = 0 ; j < al.size() ; j++ )
                                oyuncu_listesi += al.get(j) + "," ;
                                output.writeUTF(al.get(j)) ;
                    } catch (IOException e) {
                        System.err.println(e) ;
                        e.printStackTrace();
                        System.exit(1);
                    sock.close() ;
           } catch(IOException e) {
                System.out.println(e) ;
            finally {
                serSock.close() ;
        }Client
        protected void baglan() throws IOException
                Socket client ;
                ObjectInputStream input ;
                ObjectOutputStream output ;
                String line , deger ;
                try {
                    client = new Socket(InetAddress.getLocalHost() ,5000) ;
                    input = new ObjectInputStream(client.getInputStream()) ;
                    output = new ObjectOutputStream(client.getOutputStream()) ;
                        deger = girdi.getText() ;
                        output.writeUTF(deger) ;
                        output.flush() ;
                    while ( true ) {
                            line = input.readUTF() ;
                            liste.addElement(line + "\n") ;
                } catch (IOException e) {
                    System.out.println(e) ;
        }

  • Not able to flush the data output stream in n/w prg.

    Hi,
    I am trying to send and receive the data using TCP/IP channel using socket programming.
    Following is the server side code I have
    Socket socket = server_socket.accept();
    OutputStream output = socket.getOutputStream();
    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String inputMessage = (String) input.readLine();
    System.out.println(inputMessage);
    output.write("Message from server");
    output.flush();I am able to receive the message from the client and as per the code the message is getting printed in the console. But I am unable to send the message back to the Client inspite of flushing the output stream.
    I am sure that the problem is because of the flush method which is not acutally flushing the data. If I use the "println" method instead of the write & flush method, everything seems to be working fine. I do not want to use the "println" method because I get an extra new line character in the msg I send to the Client.
    Any help on this is appreciated!

    No. I am not using BufferedReader to listen for the server response. Given below is my client side code.
    Socket socket = new Socket(<ip>, <port>);
    InputStream input = socket.getInputStream();
    PrintWriter output = new PrintWriter(socket.getOutputStream(),true);
    output.println("Request from the client");
    System.out.println("Waiting for the server response...");
    byte buffer[] = new byte[2000];
    input.read(buffer);
    System.out.println(new String(byte));I am not receiving the message from server, it hangs on "Waiting for the server response..".

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

  • How can I put an output stream (HTML) from a remote process on my JSF page

    Hello,
    I've a question if someone could help.
    I have a jsf application that need to execute some remote stuff on a different process (it is a SAS application). This remote process produces in output an html table that I want to display in my jsf page.
    So I use a socket SAS class for setting up a server socket in a separate thread. The primary use of this class is to setup a socket listener, submit a command to a remote process (such as SAS) to generate a data stream (such as HTML or graphics) back to the listening socket, and then write the contents of the stream back to the servlet stream.
    Now the problem is that I loose my jsf page at all. I need a suggestion if some one would help, to understand how can I use this html datastream without writing on my Servlet output stream.
    Thank you in advance
    A.
    Just if you want to look at the details .....
    // Create the remote model
    com.sas.sasserver.submit.SubmitInterface si =
    (com.sas.sasserver.submit.SubmitInterface)
    rocf.newInstance(com.sas.sasserver.submit.SubmitInterface.class, connection);
    // Create a work dataset
    String stmt = "data work.foo;input field1 $ field2 $;cards;\na b\nc d\n;run;";
    si.setProgramText(stmt);
    // Setup our socket listener and get the port that it is bound to
    com.sas.servlet.util.SocketListener socket =
    new com.sas.servlet.util.SocketListener();
    int port = socket.setup();
    socket.start();
    // Get the localhost name
    String localhost = (java.net.InetAddress.getLocalHost()).getHostAddress();
    stmt = "filename sock SOCKET '" + localhost + ":" + port + "';";
    si.setProgramText(stmt);
    // Setup the ods options
    stmt = "ods html body=sock style=brick;";
    si.setProgramText(stmt);
    // Print the dataset
    stmt = "proc print data=work.foo;run;";
    si.setProgramText(stmt);
    // Close
    stmt = "ods html close;run;";
    si.setProgramText(stmt);
    // get my output stream
    context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    ServletOutputStream out = response.getOutputStream();
    // Write the data from the socket to the response
    socket.write(out);
    // Close the socket listener
    socket.close();

    The system exec function is on the Communication palette. Its for executing system commands. On my Win2K system, the help for FTP is:
    "Ftp
    Transfers files to and from a computer running an FTP server service (sometimes called a daemon). Ftp can be used interactively. Click ftp commands in the Related Topics list for a description of available ftp subcommands. This command is available only if the TCP/IP protocol has been installed. Ftp is a service, that, once started, creates a sub-environment in which you can use ftp commands, and from which you can return to the Windows 2000 command prompt by typing the quit subcommand. When the ftp sub-environment is running, it is indicated by the ftp command prompt.
    ftp [-v] [-n] [-i] [-d] [-g]
    [-s:filename] [-a] [-w:windowsize] [computer]
    Parameters
    -v
    Suppresses display of remote server responses.
    -n
    Suppresses autologin upon initial connection.
    -i
    Turns off interactive prompting during multiple file transfers.
    -d
    Enables debugging, displaying all ftp commands passed between the client and server.
    -g
    Disables file name globbing, which permits the use of wildcard characters (* and ?) in local file and path names. (See the glob command in the online Command Reference.)
    -s:filename
    Specifies a text file containing ftp commands; the commands automatically run after ftp starts. No spaces are allowed in this parameter. Use this switch instead of redirection (>).
    -a
    Use any local interface when binding data connection.
    -w:windowsize
    Overrides the default transfer buffer size of 4096.
    computer
    Specifies the computer name or IP address of the remote computer to connect to. The computer, if specified, must be the last paramete
    r on the line."
    I use tftp all of the time to transfer files in a similar manner. Test the transfer from the Windows command line and copy it into a VI. Pass the command line to system exec and wait until it's done.

  • Error flushing the output stream in Sun One server

    Hi All,
    I was running my servlet code in iPlanet 6.0 version and it was working fine. I upgraded my web server to new Sun One server (Oracle-iPlanet-Web-Server-7.0.9). With the new web server almost 90% of my application works fine, but there is a features in my application to download an Excel sheet by clicking a button. This feature is failing in new Sun One web server.
    Below are my piece of code and the error log I m getting. Can anyone tell me how I can fix this error, I mean is there any web server specific change or configuration parameter need to be set.
    Please ask for any information regarding my server configuration settings if needed for finding a solution for this
    Code:
    byte abyte0[] = new byte[1024];
    BufferedInputStream bufferedinputstream=null;
    BufferedOutputStream bufferedoutputstream=null;
    java.io.InputStream inputstream = httpurlconnection.getInputStream();
    bufferedinputstream = new BufferedInputStream(inputstream);
    bufferedoutputstream = new BufferedOutputStream(httpservletresponse.getOutputStream());
    int j;
    long byteCount=0;
    while((j = bufferedinputstream.read(abyte0, 0, 1024)) != -1)
    byteCount=byteCount+j;
    if(logger != null && logger.traceOn())
    logger.log("total"+byteCount);
    logger.log("Read bytes:"+j);
    bufferedoutputstream.write(abyte0, 0, j);
    if(logger != null && logger.traceOn())
    logger.log("Wrote bytes:"+j);
    bufferedoutputstream.flush(); // <<<<<< ERROR POINT >>>>>>
    Error Log :
    ClientAbortException: java.io.IOException: WEB8004: Error flushing the output stream
    at org.apache.coyote.tomcat5.OutputBuffer.doFlush(OutputBuffer.java:343)
    at org.apache.coyote.tomcat5.OutputBuffer.flush(OutputBuffer.java:313)
    at org.apache.coyote.tomcat5.CoyoteOutputStream.flush(CoyoteOutputStream.java:147)
    at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:124)
    at com.reuters.bdec.as.ASRequestHandler.processResponse(ASRequestHandler.java:285)
    at com.reuters.bdec.as.ASRequestHandler.initiateGetRequest(ASRequestHandler.java:89)
    at com.reuters.bdec.as.ASRequestHandler.proceedToDestination(ASRequestHandler.java:220)
    at com.reuters.bdec.as.ASExtension.authorisationCheck(ASExtension.java:84)
    at com.reuters.bdec.as.ASExtension.doGet(ASExtension.java:114)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:794)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:915)
    at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:398)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
    at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:255)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:586)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:556)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:187)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:586)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:556)
    at com.sun.webserver.connector.nsapi.NSAPIProcessor.service(NSAPIProcessor.java:160)
    Caused by: java.io.IOException: WEB8004: Error flushing the output stream
    at com.sun.webserver.connector.nsapi.NSAPIProcessor.action(NSAPIProcessor.java:243)
    at org.apache.coyote.Response.action(Response.java:197)
    at org.apache.coyote.tomcat5.OutputBuffer.doFlush(OutputBuffer.java:339)
    ... 20 more

    Don't flush it yourself. The servlet container will automatically flush for you once its send buffer is full. You can change the size of the send buffer though.

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

  • Exception writing binary data to the output stream to client -Broken pipe

    Hi,
    I am trying to use the drag & drop feature using Contributor mode of Webcenter sites. Single Image Page Attribute is working properly where as Multiple Image Page Attribute throws the following error:
    [ERROR] [.kernel.Default (self-tuning)'] [logging.cs.satellite.request] Exception writing binary data to the output stream to client 10.191.117.106
    java.net.SocketException: Broken pipe
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
         at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:568)
         at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:539)
         at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:427)
         at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:648)
         at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:333)
         at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148)
         at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:148)
         at COM.FutureTense.Servlet.ServletRequest$OutputOutputStream.write(ServletRequest.java:80)
         at COM.FutureTense.Servlet.ServletRequest.write(ServletRequest.java:1633)
         at com.openmarket.Satellite.RequestContext.write(RequestContext.java:1123)
         at com.openmarket.Satellite.BytePiece.stream(DataPiece.java:253)
         at com.openmarket.Satellite.CacheObjectImpl.stream(CacheObjectImpl.java:651)
         at com.openmarket.Satellite.Http11Responder.respondForWrapper(Http11Responder.java:142)
         at com.openmarket.Satellite.WrapperAwareResponder.respond(WrapperAwareResponder.java:36)
         at com.openmarket.Satellite.SatelliteServer.execute(SatelliteServer.java:85)
         at com.openmarket.Satellite.servlet.BaseServlet.doGet(BaseServlet.java:118)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
         at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
         at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
         at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at com.fatwire.wem.sso.cas.filter.CASFilter.doFilter(CASFilter.java:557)
         at com.fatwire.wem.sso.SSOFilter.doFilter(SSOFilter.java:51)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3730)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
         at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
         at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
         at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
    Thanks
    KarthiK

    Thank u very much,
         FileOutputStream opGif = new FileOutputStream(destFile, false);
    I have changed above line with the following line:
         PrintWriter opGif = new PrintWriter ( new FileWriter(destFile, false));
    and now this code is working very fine.
    Thanks once again...

  • How to print an output stream on console.

    Hi,
    I am new to JAVA. I am trying to execute a command in runtime and I want to print the output on console and also redirect the output to a file.
    Could anyone please help me?
    This is what I wrote :
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("cmd /c ipconfig");I am getting an output stream by : proc.getOutputStream(). I dont know how to print it on console and also how to redirect it to a file.
    Could anyone please help me.
    Thanks in advance.
    Basav

    You can do it this way :-
         public static void main(String args[]) throws Exception {
              ProcessBuilder builder = new ProcessBuilder("ipconfig", "/all");
              Process process = builder.start();
              BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
              FileWriter writer = new FileWriter(new File("C:/ipconfig.txt"));
              String str;
              while ((str = reader.readLine()) != null) {
                   System.out.println(str);
                   writer.write(str + System.getProperty("line.separator"));
              writer.close();
              reader.close();
         }Let me know if it works for you.

  • Java Input and Output streams

    I have maybe simple question, but I can`t really understand how to figure out this problem.
    I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
    from mobile phone:
    out.writeUTF("GETIMAGE")
    getImage();
    form computer:
    reply = in.readUTF();
    if(reply.equals("GETIMAGE")) sendimage()
    But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
    Please explain how to correcly solve such problem?
    Thanks,
    Ervins

    Eh?
    TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
    Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
    int type = dataInputStream.read();
    int length = dataInputStream.readInt();
    byte[] buffer = new byte[length];
    int count, read = 0;
    while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
    read += count;
    // At this point we either have:
    // type == -1 || count = -1 => EOF
    // or count > 0, type >= 0, and buffer contains the entire packet.
    switch (type)
    case -1:
    // EOF, not shown
    break;
    case COMMAND: // assuming a manifest constant somewhere
    // process incoming command
    break;
    case IMAGE:
    // process or continue to process incoming image
    break;
    }No threads, no polling, and nuthin' up my sleeve.
    Modulo bugs.

  • How to read unix standrad pipe output stream

    I want to write some code that will read data from a standard solaris pipe output stream. Please help.
    For example
    I cat a file in a unix shell
    cat /etc/hosts
    The output of this file can be piped to another program and I want to write a piece of code that reads that piped data and puts it into a textArea.
    Thanks

    Here ya go bro.................
    This just checks if IO is coming in and if so prints it to the term, but
    you get the idea.
    There might be an better way but...........
    import java.io.*;
    class xxx
    public static void main(String args[])
    byte b[] = new byte[256];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
    if(System.in.available() > 0) {
    System.in.read(b);
    baos.write(b,0,256);
    System.out.println(baos.toString());
    else
    System.out.println("No pipe being layed");
    catch(Throwable t){}

  • PDF Document as an Output Stream.

    Hi,
    I have created a PDFwriter class that easily creates and writes a PDF document stream to a fileout stream.I am using JSP to do the same.
    What i want to do now is directly send the stream to an output stream instead of a fileoutput stream. Question is which one??
    How do i pass it to response obj, (response.setOutputStream(System.out) does not work)
    I am Pasting some code so that you can understand what i mean( >> means next step)
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 30, 20); >>
    File file = new File("C:\\ePro\\PDFGenerator\\Report.pdf"); >> document.open();
    Table table = new Table(9); >> table.setPadding(0); >> table.setSpacing(1); >>
    table.addCell(new cell ("Any String",fontF); >> document.add(table); >> document.close(); >>
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    The above code creates a PDF file on my disk which i can then redirect. Eg
    response.setContentType("application/pdf");
    response.sendRedirect("Report.pdf");
    What i want now is to replace the constructor for PDFWriter with a different Output stream and directly write it to browser.
    Please help as i am stuck for quite some time now....

    byte[] pdfContent = PDFProcessor.getPDFStream(roleID,report,Integer.parseInt(languageID));
    response.setContentType("application/pdf");
    ServletOutputStream out = response.getOutputStream();
    System.out.println("Writing PDF");
    out.write(pdfContent);
    out.flush();

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

  • 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]);

Maybe you are looking for

  • How do I share purchased movies with family members?

    Can I share a purchased movie or TV show with other family members NOT using Home Sharing?  Can I transfer the purchase (like a gift) to someone else?

  • Problems with N97 after upgrade to v11 software

    Hi, after upgrading to v11, I thought I found my N97 slower. For example, the time take from the click of the "New message" icon till the time the SMS message writing app is ready for input can sometimes take like 3 seconds. Does any have a similar e

  • Mavericks (10.9.1) crashes & freezing

    Hi, 1 time for week my iMac (27 i5 2,9GHz, 8GB RAM, nVidia GeForce GTX 660M e Fusion Drive) FREEZE and i must RESTART !!! Here the log of today, from few minutes before the CRASH to the REBOOT: 30/01/14 12:14:55,094 icbaccountsd[3229]: -[ICBLocalDict

  • Revenue at fixed exchange rate and Tax at current exchange rate.

    Hello, We have a requirement wherein a foreign currency sales order is negotiated at fixed exchange rate.  At the time of billing while revenue should be booked at negotiated exchange rate, tax(mwst) should be calculated at current exchange rate. Is

  • Add fiscalyear./period field in one of the datasource

    I need your quick suggestion, how to create Function module and Write the code for a datasource. I want to add fiscalyear./period field in one of the datasource. please tell the logic which field and what table i will pick that. can you tell me the s