Reading from a socket that requires an EOF.

I'm trying to send a request and get a response from a socket.
The server only seems to send the response once it gets an EOF. The only way I can seem to get an EOF is to close my output stream. However, when I close my output stream before reading from the input stream I get a "java.net.SocketException: Socket closed" exception.
Is there a way to send an EOF signal in the output stream? Am I doing something wrong?
        Socket sock = new Socket(this.getHost(), this.getPort());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());       
        DataInputStream is = new DataInputStream(sock.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String responseString = new String();
        if (sock != null && os != null && is != null) {
            os.writeBytes(request);
            String responseLine;
            while ((responseLine = reader.readLine()) != null) {
                responseString += responseLine;
        } //endif
        os.close();
        is.close();
        sock.close();

Thanks for the reply. Is there no way around that? I don't have direct control over the server.
I don't understand why I can't close the socket's input stream and still read from its output stream.
Edited by: philgmo on Feb 18, 2008 3:20 PM

Similar Messages

  • Trying to read from a socket character by character

    Hi all,
    I have a problem with reading from a socket character by character. In the code shown below I try and read each character, and then write it to a file. The information sent to a socket sent from a file, and EOF is marked with character of ascii code 28 (file separator). However using BufferedReader.read() I get -1 forever. Is it reading only the last character to have been sent to the socket?
    As a side note, if I use readLine() (making sure the socket is sent a newline at end of msg) I can get the message fine. However, I want to be able to receive a message with 0 or many newlines in it (basically contents of a text file), so I want to avoid the readLine() method.
    Any help at all is appreciated,
    Colm
    CODE SNIPPET:
    try
    serverSocket = new ServerSocket(listenToPort);
    System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
    while(true)
    inSocket = serverSocket.accept();
    System.out.println("New connection accepted " + inSocket.getInetAddress() + ":" + inSocket.getPort());
    input = new BufferedReader(new InputStreamReader(inSocket.getInputStream()));
    fileOutput = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Ready to write to file: " + outputFilename);
    //receive each character and output it to file until file separator arrives
    while(!eof)
    inCharBuf = input.read();
    System.out.print(inCharBuf);
    //check for file separator (ASCII code 28)
    if (inCharBuf == 28) eof = true;
    //inChar = (char) inCharBuf;
    fileOutput.write(inCharBuf);
    System.out.println("Finished writing to file: " + outputFilename);
    inSocket.close();
    catch (IOException e)
    System.out.println("IO Error with serverSocket: " + e);
    System.exit(-1);
    }(tabbing removed as it was messing up formatting)

    My guess is that the code that is writing to the
    socket did not flush it. You said in one case you
    could read it (via readln) if the writer was writing
    lines (writeln flushes, I believe). Are you writing
    the exact same data to the socket in both tests?woo hoo, I hadn't flushed the buffers alright!
    for anyone with similar problems, I was missing this from my write-to-socket method:
    output.flush();
    where output was the BufferedWriter I had created to write to the socket.
    Thanks a lot for pointing it out!
    Colm

  • Trying to veiw videos from a website that requires me to download firefox and silverlight.My imac osx 10.5.8 will now download firefox. firfx tells me my mac is not compatible with ffox Please help me ?  Thank you

    trying to veiw videos from a website that requires me to download firefox and silverlight.My imac osx 10.5.8 will now download firefox. firfx tells me my mac is not compatible with ffox Please help me ?  Thank you

    There is a version of Firefox 4 available for PPC Macs:
    TenFourFox 4.0.1 Firefox 4 For PowerPC Browser Released
    Version 4.0.1 of TenFour Fox, FloodGap's port of Firefox 4 for Power PC
    Macs that supports both Mac oS X 10.4 and 10.5. has been released.
    Mozilla.org dropped support for OS 10.5 after Firefox 3.6 and for Power
    PC with the fourth beta of Firefox 4.
    TenFourFox uses almost all the same code as Firefox 4 and has nearly all
    the same features, including faster JavaScript, WebM video, and HTML 5
    and CSS 3 support, as well as new and emerging Web features, but with
    the code needed to keep your Power Mac functional and fast. Out of beta
    and it's ready for action, versiob 4.0.1 is a performance, security and
    stability update incorporating Mozilla's Firefox 4.0.1 plus AltiVec acceler
    -ation for WebM and browser graphics, and G5 JavaScript acceleration.
    For more information, visit:
    http://www.floodgap.com/software/tenfourfox/
    Source: from http://www.applelinks.com - posted April 25, 2011)
    Now for the intersting bit: TenFourFox, like Firefox, does not support most plug-ins. Unless you are prone to headaches (in which case don't) you can read about that here:
    http://code.google.com/p/tenfourfox/wiki/PluginsNoLongerSupported
    But there is a workaround!
    Open TenFourFox and type in the address bar: about:config (no spaces) and click return. This gives you a warning that it might harm the application. Ignore that and click on 'I'll be careful, I promise' and you get the config file that you can edit - with great care.
    Look/search (scroll down) for: tenfourfox.plugins.enabled
    Set it to true. (Double click it to toggle it)
    Now close TenFourFox, open it again, and Flash will now work, as it now uses the plug-ins that Safari has stored.
    With SilverLight, Microsoft attempted to create their own version of what a replacement for Flash could be - but not to universal acclaim. You can read more about it here:
    http://silverlight.net/
    So, if you go to any sites that have been designed for this new Silverlight stuff, you can download the plug-in from here (but make certain that you are downloading SilverLight v.1.0 for OS X (10.4.8 upwards) if you are using a PPC Mac, but even this will not work with Safari 4. Version 2 only works with Intel Macs and does work with Safari 4/5. The solution is to download and install the latest version of Flip4Mac, which now includes a Silverlight component:
    http://dynamic.telestream.net/downloads/download-flip4macwmv.htm
    But the latest news is that Microsoft will probably abandon Silverlight in favour of HTML5:
    http://www.appleinsider.com/articles/10/10/29/apples_ios_pushes_microsoft_to_dia l_down_silverlight_for_html5.html  and
    http://www.bbc.co.uk/news/technology-11673384

  • I would like to use slideshow in lightroom to export my video as a full screen 1920x1080 video with text overlays.  I am using text overlay in lightroom as it reads from the metadata that is easy for me to input in the library screen.  When i export from

    I would like to use slideshow in lightroom to export my video as a full screen 1920x1080 video with text overlays.  I am using text overlay in lightroom as it reads from the metadata that is easy for me to input in the library screen.  When i export from lightroom slideshow and choose the 1920x1080 resolution the end product is a very small video in the middle of a black background.  i have double checked and do not have any borders turned on.  Another option would be to export from the library but lr mogrify does not seem to put text overlays on video either.  Any input would be welcome.

    I dont understand anything you said in your post.
    Do you have a specific question about video production?
    The forums are for individual technical or creative issues that users have with video production. I am sur someone will be able to help you, but and to get a response it is best to ask a specific question.
    Is this about a technical problem you have or something about setting up a web site? If its the latter this is the wrong forum.

  • Parsing XML from a socket that does not close

    Hi -
    I've seen similar questions to this already posted, but either they did not really apply to my situation or they were not answered.
    I have to read messages from a server and process them individually, but the protocol does not indicate the message length or give any sort of terminating character. You only know you have a complete message because it will be a well formed XML fragment. To complicate matters more, there could be extra binary data preceding each XML message. I must stress that I did not write this server, and I have no influence over the protocol at all, so while I certainly agree that this is not such a good protocol, changing it is not an option.
    I'm hoping that there is a reasonable way to deal with this with an existing parser. Ironically, I don't really need to parse the XML at all, I just need to know when the current message is over but the only indication I get is that it will be the end of an XML fragment.
    I do have the ability to strip off the non-XML binary data, so if there is some way that I can give the stream to a SAX (or other) parser when I know XML is coming and have it inform me when tags begin and end, or ideally inform me when it is done a complete XML fragment, that would be perfect. I'm aware of how to do this using SAX normally, but it seems that it will not function correctly when there is no EOF or other indication that the document has ended.
    The best algorithm I have come up with (and it's pretty cheesy) is:
    1. Start with a string buffer.
    2. Append data from the socket to the buffer one byte at a time.
    3. Keep checking if there is a '<' character that is not followed by '?' or '!'. (ie - don't concern myself with the special XML elements that don't close with '/>' or </tagName>. I keep them in the buffer to pass on when I'm done though.)
    4. When I get my first tag with <tagName> I make note of what this tag is and increment a counter. If the tag is self closing, then I'm done.
    5. Anytime I see this tag I increment the counter.
    6. Anytime I see </tagName> I decrement the counter. If the counter = 0, I am done.
    7. I pass on the entire message, preceding binary data, special XML tags and the fragment to the module that actually processes it.
    This has a few problems. I'll have to go out of my way to support multiple character encodings, I'll have to be careful to catch all the special XML tags, and its quite CPU intensive to be interested in every single character that comes down the pipe (but I suppose this is not avoidable). Also, I just don't like to re-invent the wheel because I'm likely to make an error that a well established parser would not make.
    Does anyone have any suggestions for this, or know of a parser that will deal with fragments using streams that don't close?
    Thanks!

    The parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.

  • Sockets: How do I know how much I can read from a socket?

    Hi everyone,
    I've opened a socket connection to a cisco router and want to read some of its databases. These are the main part of my code:
    Socket so = new Socket(routerIP, routerPort);
    BufferedReader br = new BufferedReader(
    new InputStreamReader(so.getInputStream()));
    BufferedWriter bw = new BufferedWriter(
    new OutputStreamWriter(so.getOutputStream()));
    // user/password entered.
    bw.write("show ip alias\r\n");
    bw.flush();
    while ((in = br.readLine()) != null) {
    System.out.println(in);
    so.close();
    The problem occurs in the "while" loop at the end of the code. The last line that the router is sending doesn't have a \r\n at the end and therefore my readLine command waits indefinitly.
    Well, I guess I can change that command with a simple read but still it won't be general. I'm looking for a command like "available" in socketImpl that tells me the number of bytes that I can read from the server beforehand.
    Any solutions?????????????
    Thanks,
    Ali.

    Ok, that much I know from the router. It supports
    telnet. So, basically if a telnet client can tell when
    it has read all the data coming from the router and
    when it has to wait for user to input the data, I have
    to be able to do so too.Hi, telnet does not know that it has read all the data coming from the router or from you; It waits for data from both sources (the router and you), and then retransmits that data to (you or the router respectively.)
    telnet must be sending and receiving data byte by byte
    cause what we type is displayed on the screen if the
    server echos the characters back to the client.
    Any suggestions, anyone knows of a simple telnet
    source?True. In particular, telnet does not care whether there is any carriage return or linefeed characters. It just retransmits whatever it gets from the source to the destination, except that it looks for particular escape sequences from the data source, such as the sequence for shutting out echo when you enter passwords.
    In your case, I am not sure what you want to achieve. I think you are trying to find the end-of-data but the end-of-data is not unambiguously terminated by an end-of-line. Maybe you need to find some other character or even strings for that purpose. You may even need to process the whole data received in order to determine the end of it.
    However, if you just want just that answer from the router and no more, you can send your logout after your query, so that after the router replies your queries, it also closes the connection and your BufferedReader.readLine() will return.

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

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

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

  • How to read from txt file that has words in between?

    Hi all,
    I am using Labview 8.2.
    I would like to read from a text file.  I have data (after each time it is has averaged over 100 waveforms) repeatedly stored on to the file.  The idea is to further improve SNR in post processing by again averaging the data (that has been averaged over the 100 waveforms).  
    I can get LabView  to save the data repeatedly into the file, so it keeps getting appended.
    The problem is to read the data in labview so I can now again average it.  The problem is the labview seperates the sets of data with the following:
    " Channels    1    
    Samples    9925    
    Date    2008/10/28    
    Time    17:16:11.638363    
    X_Dimension    Time    
    X0    -3.0125000000000013E-3    
    Delta_X    2.500000E-6    
    ***End_of_Header***        "
    So When I read it, it only sees the first set of data.
    Can someone please tell me how to read all the sets of data in labview?
    I have attached the file I want to read "acquiredwaveform.txt"  and the basic VI (really basic btw) to read the file.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    ReadFileAndAverage.vi ‏48 KB
    acquiredWaveform.txt ‏605 KB

    Thanks again DFGray for the comments. 
    After the correlations to find the peak positions, i just take the max value.  And you are right the accuracy is limited by the number of  samples per cycle.  Perhaps it would be clearer if you see the code.
    1) Basically I get a signal on the up and downslope of the sine wave.  On the down slope however the signal is negative, i.e. its is flipped.  So before I shift and average...I 'cut' the waveform into 4 (when cycles per buffer = 2, then I get 4 signals, 2 on the up slope and 2 on down slope) bits.  Counting from one, I flip the even number, cut it, and but an array of waveforms which is then sent to be convolved and shifted.
    2) Array of waveforms are stored to be phased shifted (Convolve and shift vi) and averaged (entire averaging vi which uses the convolve and shift vi as a sub vi). 
    * Phase shifting doesn't work when I cut and put it together (So something is wrong in cut waveform vi) 
    * Also if it isn't too time consuming could you give me an example of interpolating and shifting thing.
    * Also if you have any comments regarding the following VIs please let me know.  
    Thanks 
    Attached is:
    1) Cut waveform vi
    2) Convolve and shift
    3) Entire averaging 
    Attachments:
    SubVICutWaveforms.vi ‏37 KB
    SubVIConvolveShift.vi ‏30 KB
    SubVIEntireAveraging2.vi ‏43 KB

  • Can I download Mavericks installer from a machine that requires Yosemite?

    I would like to download the OS X Mavericks installer, but the only Mac I can currently connect to the Internet is too new to support Mavericks, so it tells me I can't even download it. I am trying to acquire it to prepare bootable install media for a machine which is without Internet access.

    No. Mavericks is no longer available for download or purchase. Even were you to get Mavericks you cannot install it on a model that requires Yosemite or later.
    The machine without Internet access would not be able to download Mavericks either.

  • Stop blocking read from a socket but still preserve it

    Hello, I have a thread waiting for a socket input...in case I wanted to stop it I need a way to stop blocking receive, but not something like close() or shutdownInput() because I don't want to close the socket but simply shut down the thread...any ideas?

    It sounds like you need to set a socket read timeout: see Socket.setSoTimeout(), but exiting the thread and leaving the socket to another thread doesn't sound right. Normally the thread is dedicated to looking after that socket.

  • Parsing Content From A Site That Requires Authentication

    Ive been scanning websites using the Java HTML parser from htmlparser.sourceforge.net to gather useful data into a more easily used format, in this case it is stored in a mySQL database.
    The problem that has stumped me for the past few days is how to get around the login authenication page required to access content from the website www.racingpost.com . I am a registered user but am having difficulty logging in via Java and managing the cookies to bypass the login page HTML I keep getting instead of the race data.
    I am unsure when and where I should be passing cookies around. Also logging in using POST is confusing me.
    Thanks for any help you can offer.

    this should help you out with posting to a URL. It is taken from:
    http://javaalmanac.com/egs/java.net/Post.html
    // e135. Sending a POST Request Using a URL
        try {
            // Construct data
            String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
            data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
            // Send data
            URL url = new URL("http://hostname:80/cgi");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                // Process line...
            wr.close();
            rd.close();
        } catch (Exception e) {
        }

  • Insert symbol from dropdown list that requires font change

    I am trying to script the following:
    I have a dropdown list set to GDT font which contains symbols. (GDT font creates symbols with various lower case letters are entered)
    When selecting a symbol from the dropdown list, I want that symbol to be inserted into the textfield where I stopped typing text and the cursor is currently positioned. The text I typed is using the Myriad Pro font, so to insert the symbol, the script needs to change the font to GDT without affecting the text font that is already typed in the textfield, insert the GDT font symbol and then change the GDT font back to Myriad Pro so I can continue to type more text in Myriad Pro.
    If the script would just copy the symbol and the font it was created in, paste it where the cursor is position and then change the font back to the default (Myriad Pro), that would be great!
    This is for Design Engineering work to allow engineers to insert GDT symbols into the same textfield as their description is in.
    Can anyone help me with this script?

    Troubleshooting plugins
    * https://support.mozilla.com/en-US/kb/Troubleshooting%20plugins
    Check and tell if its working.

  • SocketException thrown when reading from socket.

    I got a thread that listen on a socket for data with: while (LISTENING)
    new AAAcknowledgeThread(serverSocket.accept()).start();
    When the thread mentioned executes and tries to read from the socket with:
    BufferedReader in = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));
    A SocketException is thrown with the following stacktrace:
    java.net.SocketException: Connection reset by peer: JVM_recv in socket input stream read
    at java.net.SocketInputStream.socketRead(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.InputStreamReader.fill(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at se.ericsson.era.psem.jms.plugins.AAServerSimulatorThread.run(AAServerSimulatorThread.java:67)
    Does anybody know what could cause my problem?

    If you are creating the Socket in another Thread then I don't think the thread you create can read from that InputStream/OutputStream. I remember doing something like this while transfering files through RMI. I was openning a File and passing the FileOutputStream to another thread that pulled the file through RMI. That thread couldn't write to the outputstream, and would throw an exception. When I let the thread open it up. It worked.
    charlie

  • 100% CPU Utilisation while reading from socket

    I have writted a ServerSocket program to read data from ethernet client bridge. client-bridge is a system which converts serial data to TCP packet and vice versa. I can read from the client bridge only through creating a server socket and waiting for the client bridge to make a client socket connection (ServerSocket.accept() method.
    The problem that I m facing is that, the client bridge is creating connection only once. I have created an infinite loop which keeps on reading from the socket. The performance of the application goes down drastically (100% CPU utilisation through task manager) when this application is run. Is there a better way of reading data from the client bridge. The client bridge is not in our control and the server can only wait for the client to make connection.
    Please help. Thanking you all in anticipation.
    Regards,
    Amitabha

    If I close the client socket will the client create a new socket to
    transmit data or it depends on the client application.
    I have also tried creating a new socket connection for
    reading each frame of the protocol. but the client
    creates only one socket. What might be the problem?I bet it depends on the client app because your server app only waits for a connection from the client. So it's the client that initiates the connection. When you disconnect the client socket then you will have to wait for another client request. what you can do is to stay connected (unless of course client disconnects itself) and just keep on reading from the client socket.

  • Diffference between reading from URL and reading using Sockets

    Hi,
    For my AJAX call, if the URL is out side my domain, then I am not able to get the js and css for that url.
    what can be the other approaches to resolve this issue?
    again, what is the difference between reading from URL / reading from a socket connection?
    Does AJAX call through socket solve my problem??
    Your input is appreciated.
    Thank you,
    Regards,
    Chintan

    Converting Between a Filename Path and a URL
    Copying One File to Another

Maybe you are looking for

  • Cannot delete old apple device software update file from trash

    I restored a new iPad from an old one and now there is an .ipsw file with the is08 8.0.2 update and I cannot delete it even tried command secure delete and option secure delete. The file is grayed out and says it is in use by another application. Ple

  • Question on hyperlinks

    Hi All, I'm working on a report which is like a dash board, it is a summary report which has many columns eg: coffee, chocolate etc. These summary columns i.e chocolate coffee etc have scorecards which is the detail of the summary. the requirement is

  • Merging multiple forms and having shared fields

    I am designing multiple forms for a client for application purposes.  There are about 40 forms in all. Client is designing a online helper that will help users download only the forms they need for their application.  So once that is decided, then we

  • Changing multiple clips

    I have figured out that I can paste an effect across multiple clips... but I have not figured out how to change, for instance, a "Motion" attribute like "Opacity" across multiple clips at once... is there a trick I'm missing, or do I need to pick a s

  • How to prevent JEditorPane to show remote images

    Hello I make an e-mail client with JEditorPane to show the html content. If the content contains IMG tag with src like http://somehost.on.the.web... then JEditorPane tries to load the remote image. But I have an internet connection via proxy. So, JEd