Httpurlconnection chunked output stream?
Hi,
I'm developing a client that interacts with a comet server (comet allows http connections to be used for multiple inputs and outputs on same connection -- not single request, single response). I've found that I can't use HttpURLConnection because it doesn't allow writing to its output stream after any input has been read from its input stream. It seems that httpURLConn.getInputStream() basically closes the output stream. Is there any way around this? Any way to write to an httpurlconnection's output stream after a read on its input has occurred?
For now I have to resort to using raw sockets and dealing with headers and chunked encoding manually. I'd sure love an easier way...
Thanks for any help,
Peter
Get a new HTTPURLConnection. Java will cache it behind the scenes to reuse the same TCP connection.
Similar Messages
-
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 moreDon'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.
-
Buffered input/output stream
How the buffereing is done in buffered input/output streams?
From the API doc I got to know that they use internal buffer to store bytes before they can be read or written. But i found that File input/output stream also have methods like read(byte[]) or write(byte[]). So what is extra in buffered input/ouput streams? Does the phrase "buffered" suggests that bytes can be read from an array or be written to an array? Am i thinking the right way?How the buffereing is done in buffered input/output
streams?
From the API doc I got to know that they use internal
buffer to store bytes before they can be read or
written. But i found that File input/output stream
also have methods like read(byte[]) or write(byte[]).Thouse are your buffer, not the streams'.
So what is extra in buffered input/ouput streams?
Does the phrase "buffered" suggests that bytes can be
read from an array or be written to an array? Am i
thinking the right way?No. It means that the stream either prefetches some data even if it's not requested yet, or that it withholds data that it's supposed to write until it's flushed or gets a larger chunk. -
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. -
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. -
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
KarthiKThank 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... -
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 methodhi 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 -
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.
BasavYou 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. -
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,
ErvinsEh?
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.
ThanksHere 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 postingYes 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]
Maybe you are looking for
-
In iCal, what is the little balloon on the side of some calendar days?
I'm using iCal Version 3.0.5 (1270). On some of my calendar pages, a tiny balloon has appeared in the column where the times of the day are listed, with a horizontal line extending to the right from the balloon across the calendar page. Nothing happe
-
My DVD Stduio Pro File is waay too big
Hi all, I have imported a bunch (1 hour and 40 minutes worth) of .m2v and .aiff files into DVD Studio Pro. In the space cache in DVD Studio Pro it says I have 6.4 gigs of material. Is there any way to compress my files in the exporting process of bui
-
I reinstalled cs2 after my laptop crashed, now when I open illustrator it exits immediatly with out warning. It does not give any errors, it just closes within 2 seconds of opening. Any ideas on fixing this problem?
-
Address book froze when I merged duplicated data. When I force quit the application and reopened it, I was unable to search my contacts. I would type in a name, but it wouldn't search, even if I hit enter. Furthermore, after I attempt to search my co
-
hi guys i have a v basic question i have got ccnp on me and now i m v much interested in doing voice track.....i m making a lab for ccvp now i want to replicate the true scenario it would be two sites with ccm servers on each site....so i have to buy