Read byte stream from socket

Hi, i must create a socket to a telnet server. I must read the server answer. How can i read the input stream and print it? The server's response is not necessarily a line.
Thanks,
Andrea

{http://bytes.com/groups/net-c/629260-reading-network-socket-stream-slow-connection                                                                                                                                                                               

Similar Messages

  • How to read bytes(image) from a server ?how to display image after read byt

    How to read bytes(image) from a server ?how to display image after reading bytes?
    i have tried coding tis , but i couldnt get the image to be display:
    BufferedInputStream in1=new BufferedInputStream(kkSocket.getInputStream());
    int length1;
    byte [] data=new byte[1048576];
    if((length1=in1.read(data))!=-1){
    System.out.println("???");
    }System.out.println("length "+length1);
    Integer inter=new Integer(length1);
    byte d=inter.byteValue();

    didn't I tell you about using javax.imageio.ImageIO.read(InputStream) in another thread?

  • Read a line from socket

    i am new in java and also new in network programming in java..
    i would like to read aline from socket, for that i had written the code just like below
    ServerSocket serverSocket
    clientSocket = serverSocket.accept();
    DataInputStream is = clientSocket.getInputStream();
    String take=is.readLine();
    i got an error the method readLine() is not..

    i got an error the method readLine() is not.. is not what?
    And also, did you even bother to read DataInputStream's documentation to see what it's useful for? If not, go and do it. And while you're at it, also look at InputStreamReaders/BufferedReaders.

  • Interpret a byte stream from a Bluetooth-device

    Hi
    I'm having a problem with interpreting an InputStream from my Bluetooth device. I'm developing an application on SE P900, J2ME MIDP2.0/CLDC 1.0.
    Example:
    while((read = is.read(byteArray)) != -1) {
       receivedData = new StringBuffer();
       log("Read:  " + read + "bytes");
       for(int i = 0; i <= read; i++) {
          byte tmp = (byteArray);
    receivedData.append(tmp);
    log(receivedData.toString());
    log("Finish :)"); //This is never printet. read is never -1..
    //The result of my app in P900:
    //Read 2 bytes
    //3100
    //Read 2 bytes
    //0310
    The bytestream I get from the bluetooth-device looks something like this:
    byte 0: header
    byte 1: MSB
    byte 2: LSB
    byte 3: CRC
    I need to find out how I can interpret the inputStream correctly! It is possible that my output is wrong, so that the input is incomplete. But it'd be much easier if I could read the InputStream correct
    I've also tried to use the InputStreamReader, since it converts bytes to unicode, but that wont work. Have got a few examples on that, but in J2ME the BufferedReader doesn't exists so I cant it out
    Haavard

    simple:
    byte header = Datain.readByte();
    short length = Datain.readUnsignedShort();
    byte[] IDinBytes = new Byte[length];
    Datain.readFully(IDinBytes );
    String ID = New String(IDinBytes );this might also work:
    byte header = Datain.readByte();
    String ID = Datain.readUTF();but this is really hack, since readUTF() will first read two bytes to indicate the length of the string, and then the string itself. In this case, it works, but in general you should use the first example. Only use readUTF() if you have DataOutputstream on the other side that uses writeUTF(), in all other options, it's more or less a dirty hack ;)

  • Read console symbols from socket...

    hello
    i have a socket the connects to a chat server (buzzen.net) if any one know it...
    when i read from that socket in telnet, i get some nicknames in symbols (those u can get by openning cmd console, holding ALT key and hiting numbers then release ALT)
    i want java to read this symbols correctly, when i read them it gave me the letters that represent them but i want the original symbols so i can communicate with the server.
    the server encoding is UTF8, in the telnet it works fine, but in java it converts them... i need to get the characters as sent from the server.

    i got an error the method readLine() is not.. is not what?
    And also, did you even bother to read DataInputStream's documentation to see what it's useful for? If not, go and do it. And while you're at it, also look at InputStreamReaders/BufferedReaders.

  • Parsing input stream from a socket

    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    Thanks,
    Andrea

    andmus wrote:
    Hi, i must read a byte stream from a socket. My problem is that i cannot determine when a stream ends because there are no terminator characters. I tried to use the read() method of BufferedReader class but it blocks when server statement ends. Is there a way to read the stream and answer to the server?
    If you're reading HTTP...
    Unless the request has been sent with Connection: close, it's normal that your read blocks, since the connection is purposefully left open to accomodate further exchanges.
    You'll have to parse the data to know when each message is complete. The first empty line (bytes: \r\n\r\n ASCII) denotes the end of the header. The header will have a Content-Length property which tells you how many bytes are left to read.
    Google the HTTP specs if you don't know them.

  • Failed to read bytes from InputStream

    Hi,
    I get this excpetion log when I try to read a stream from weblogic. Can anyone help me out why this happens and what
    could be done to overcome this
    ####<Aug 8, 2007 4:48:37 PM EDT> <Error> <HTTP> <sundev01> <fhsserver> <[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1186606117277> <BEA-101019> <[weblogic.servlet.internal.WebAppServletContext@111f9b - name: 'FFMS', context-path: '/FFMS'] Servlet failed with IOException
    java.io.IOException: failed to read '2678' bytes from InputStream; clen: 58512 remaining: 44902 count: 1394
    at weblogic.servlet.internal.ChunkOutput.writeStream(ChunkOutput.java:411)
    at weblogic.servlet.internal.ChunkOutputWrapper.writeStream(ChunkOutputWrapper.java:168)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:496)
    at weblogic.servlet.internal.ServletOutputStreamImpl.writeStream(ServletOutputStreamImpl.java:484)
    at weblogic.servlet.FileServlet.sendFile(FileServlet.java:400)
    at weblogic.servlet.FileServlet.doGetHeadPost(FileServlet.java:224)
    at weblogic.servlet.FileServlet.service(FileServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:225)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:127)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:272)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:165)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3150)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:1973)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1880)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1310)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:179)
    >

    Hi Aravind,
    Which version of weblogic are u using?
    Cheers,
    Lakshmi

  • Read an object stream from last

    I write objects to a file in ascending order of their creation times. Later when I want to see the latest object(i.e. the last object written to the file), I need to trasverse through all the objects to the last object. Is there a way to read the stream from the last so that first thing I read is the last object I wrote ? I dont think it is impossible. All we need to do is to come to the begining index of the object somehow from the last and then read forward as usual. Though , I dont have any clue as to how to achieve this. If you have any ideas, I would be grateful.

    Well! situation here is I dont have any such information. What I am talking about is a log file which is populated by various processes with a particular object type. I have no idea about the byte position of the last object , and so cant use skipBytes(). Any other way ?
    Thanks anyway.

  • How to set HttpURLConnection timeout while reading a stream?

    I want it got time out if the connection if lose while i read a stream from URL
    try {
         int timeout = 700;
         HttpURLConnection connection = (HttpURLConnection) downloadURl.openConnection();
         connection.setConnectTimeout(timeout);
         connection.setRequestProperty("Range","bytes=" + downloaded + "-");
         connection.connect();
         if (connection.getResponseCode() / 100 != 2) {
              error();
         int contentLength = connection.getContentLength();
         if (contentLength < 1) {
              error();
         if (status == DOWNLOADING){
              if (size == -1) {
                   size = contentLength;
              file = new RandomAccessFile(saveTmpName+".tmp", "rw");
              file.seek(downloaded);
         byte buffer[];
         stream = connection.getInputStream();
    connection.setReadTimeout(timeout);
         while (status == DOWNLOADING) { 
              if (size - downloaded > MAX_BUFFER_SIZE) {
                   buffer = new byte[MAX_BUFFER_SIZE];
              } else {
                   buffer = new byte[(int)(size - downloaded)];
              int read = stream.read(buffer); // how to set timeout while it is reading stream
              if (read <= 0)
                   break;
              file.write(buffer, 0, read);
              downloaded += read;
         if (status == DOWNLOADING) {
              status = COMPLETE;
    } catch (SocketTimeoutException  e) {
         error();
    } catch (IllegalArgumentException e) {
         error();
    } catch (Exception e) {
         error();
    } finally {
         if (file != null) {
              try {
                   file.close();
              } catch (Exception e) {}
         if (stream != null) {
              try {
                   stream.close();
              } catch (Exception e) {}
    }I try to set "setReadTimeout()" but is still not through timeout Exception

    ejp wrote:
    Because, there's no FTP client command that allows to do such thing.Socket.setSoTimeout().I agree with you on this one but the OP is talking about the FTPClient API from Apache.
    To the OP,
    BTW, I have reread the Javadoc about the [*API*|http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html] : indeed, there's no setTimeout method, but there is a setDataTimeout method : +Sets the timeout in milliseconds to use when reading from the data connection+ .

  • Can two programs recive the same stream from the same port?

    I am sending a video from a server to my client on port 23456.
    On my client I am running a videoreciver that shows the video, and I also want to run a program that receives the strem with datagramSocket and writes out statistics.. Is this possible? or wil I get: can't open local dataport..
    do I have to runn it one by one.. and maybe send the vide two times?

    What you should do is just layer the functionalities, so that you have one class that reads the stream from the port and buffers it. You can then have multiple clients that read this buffered stream.

  • Help with Sample on Converting an XML string to a byte stream

    Hello All,<br /><br />I am sure this is something simple, but I am just not figuring it out right now.<br /><br />I am following the sample - "Converting an XML string to a byte stream" from the developer guide since I want to prepopulate just 1 field in my PDF form.<br /><br />How do I reference my form field within my servlet code properly??<br /><br />I have tried a few things now, my field is within a subform, so I thought it would be <root><subformName><fieldname>My data</fieldname></subformName></root>  I have also tried adding <page1> in there too.<br /><br />I am following everything else exactly as given in the sample code.<br /><br />I do have an embedded schema within the form and the field is bound.<br /><br />Thanks,<br />Jennifer

    Well, if you have a schema defined in the form, then the hierarchy of your data must match what is described in the schema. So, can't really tell you what it would look like, but just follow your schema.
    Chris
    Adobe Enterprise Developer Support

  • Reading bytea column over dblink

    Hi,
    I try to read bytea column from postgresql db over a dblink in Oracle DB. But I could not. How can I solve the problem?
    In windows environment there is a parameter in odbc driver bytea as LO. I could not find how to set it on unix odbc.
    Versions of products I Use:
    Postgresql 8.3.3 on redhat
    Oracle DB : 10.2.0.4 on HP/UX
    HSODBC : 10.2.0.4

    CURRENT_DATE is not supported:
    Supported SQL Syntax and Functions
    However, from reading this part:
    Supported SQL Syntax and Functions
    it becomes clear that you'll need to use a string of DATE datatype (in a fixed format) or select from a DATE column.
    You could just boldly try: to_date(CURRENT_DATE) , but you'll probably receive ORA-02070 again...

  • Reading bytes from a server

    Ok,
    I want to connect to a server and recieve a data from it.
    the data is broken up as follows:
    int flag;
    int x, y;
    String name;
    the server i'm communicating with is written in C, so i'm trying to figure out how i'm going to recieve this data.
    What is the size that java uses to store an integer value?
    IF java uses unicode, that's two bytes per character right?
    so if name was 30 characters long it would be 60 bytes?
    i'm thinking of trying to either read the whole transmission into one string then separate, or separate as it comes in?
    could someone suggest how to proceed>

    Java holds (primitive) integers in 32 bits.
    Java holds characters in 16 bits (two bytes)
    30 characters will occupy 30*16 = 480 bits (60 bytes)
    Java provides the java.net package for networking. In there you can find a class called Socket that identifies the clients's communication endpoint, and encapsulates a host and an application address (port).
    First you open a socket to a server:
    Socket s = new Socket( serverName, serverPort );
    then you just read an input stream from the socket.
    DataInputStream dis = new DataInputStream( s.getInputStream() );
    String message = dis.readUTF(); //wait for server to send
    s.close() // close the socket
    Now, you can do with message whatever you like. It's that simple!
    For more information you can see the related tutorials from java.

  • Reading input stream over the tcp socket in unix

    I have a program that reads data from input stream from the socket. If the data is over 1500 bytes it is sent in multiple TCP packets. Whats weird is, if I run the program in windows environment it waits till it receives all the packets but when I run the same program in unix environment it only reads the first packet and go further without waiting for all the TCP packets!!
    The line that reads from input stream is
    datalen = inStr.read(byteBuffer);is there anyway I can make it wait till it receives all the packets on unix system? I do not understand why it works fine for windows in this case but not for unix.
    I'll appreciate any help..
    Thanks

    When the network is busy there can be any amount of dleay between packets. If this is ever 100 ms , then this will break.
    If you send more than one packet per 100 ms you will get two packets at once which will look like one longer packet. Unless you check for this the second packet may get ignored.
    The safe way is to send the packet size before sending the packet. Then on the client read the packet to the correct length. Otherwise you will have a program which just happens to work rather than one which will always work.

  • Problem trying to read an SSL server socket stream using readByte().

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

Maybe you are looking for

  • Apple says dvi ro adc adapters are the problem

    I posted with the correct title, exucse me missing our thr "to adc adaptor " part. anycase They sent this person with there mac mini, 22" plastic cinema display and DVI to ADC adapter to be looked at by 4 different centers in europe, no on-sight or p

  • Why did Apple wreck our iPads, the return

    suggested (yes I know I've got two AAs, another bug is IOS 8.1 but I'm sick of having to correct the typos from the laggy keyboard so far no backup so setup as new restore via itunes software from apple install completes go through setup as new nothi

  • How to populate LOV at run time in developer

    I want to populate my LOV with with say SELECT NAME FROM MY_TABLE Also I have text item in my developer form I want to display this item depending upon the result of my query i.e If have ten record this text item would show ten records and if have el

  • About Inspection Report

    Hi experts, I want some changes in Standard Inspection Report as customer no is not there. how do i find sales order number of material and add cust. no(sold.to.party) through sales order . Is it possible to place custmer in case of material is semi

  • Checking print job status

    Hi, In Leopard, when I print to any of my printers, an application with the name of the printer I'm printing to appears. If I want to check on the status of the current print job, I can't figure out a straightforward way to look at the jobs in that p