Socket.InputStream.read()

public ServerThread(ThreadGroup t, Socket con,lServer master, int clientId) {
     super(t, "server");
     this.con = con;
     this.master = master;
     this.clientId = clientId;
void run(){
    int task = 0;
    try {
        out = new DataOutputStream(con.getOutputStream());
        in = con.getInputStream();
        out.write(job.KN_NewClientID);
        out.write(clientId);
    } catch (IOException e) {
        melde("\nIOException  in run : " + e);
        return;
     * Start waiting for input
    while (true) {
        try {
       *   next line conecersn my question
       *===========================
            task = in.read();
            switch (task) {
              // more          
        } catch (IOException e) {
            System.out.println("IOException  Serverthread  : " + );
            return;
}When the above ( code-snippet) Thread is waiting for input
task = in.read();
In I create another thread, which will try to send and receive with the same socket in and -out.
does the above thread block the second ?
and if so, how do I avoid this
TIA
Hanns

i like this forum: http://forum.java.sun.com/forum.jspa?forumID=11
as for the question,
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html#sockets
what i can get from this, is have a listener, listen for new connections, every connection established, create a new thread, these threads will have their own input and output streams, so you wont have to worry bout watchyamacallits
then again, your threadgroups, im not following your code, but all i can say, is the socket examples work

Similar Messages

  • Socket InputStream read , slow performance

    Hi ,
    We have developed a java socket appliction ,
    This application will be connected to a configured client socket .
    client socket will send huge no of messages to our application , our application will receive the messages and do the need full things,and send the acknowledgement to the client.
    In order to receive the messages we are using the code like this
    public void run(){
    socket_InputSteram = Socket.getInputStream()
    while(true){
    // read the message from the connected socket input stream.
    readMessage( socket_InputSteram );
    now comes the actual problem , for some number of messages our application is stable and doing well , after some time our application is taking almost 100% CPU and very slow.
    can any body help me why our application is taking 100% CPU , why it is faster in the initail stage and it is very slow after some time . what are the necessary steps we have to take inorder to read the socket input stream.
    i would be very thank full, if any body can provide the solution
    Thanks,
    SPK Srinivas.

    Is it actually using CPU time or only wallclock time? In the latter case it's probably just waiting for more data to arrive and you should concentrate on the next method(s) in the list.
    If it's actually using up CPU, then you might want to check if you're using it inefficiently.
    Prime examples: Reading a single byte at a time. If you do something like this:
    int b;
    while ((b = in.read()) != -1) {
      // do something
    }Then you're doing something wrong and should read into a buffer (byte-array) instead.

  • Bug in the ServerSocket InputStream.read()

    I believe there is a bug in the ServerSocket InputStream.read() method.
    This is demonstrated under Windows XP, running 1.4.0_01-b03
    I am looking for confirmation and an examination of my assumptions for this.
    There is nothing that suggests the InputStream.read() method should block on a EOL, yet it does.
    This is demonstrated with the following code.
    To reproduce uncomment one of the 'Case' sections in the MyServer code. Compile both classes. Run the MyServer then MyClient code.
    The expected result for ALL cases should be
    ***socket start
    text1
    text2
    But for the first case the last line is not printed. Note that for case 3 it does work, and the only exception is that available() is called.
    The InputStream of the server resolves to java.net.SocketInputStream. The read() method calls the read(byte, int, int) method (which how I guessed that calling available would produce different results.)
    //-----------------Client
        import java.io.*;
        import java.net.*;
        public class MyClient
            private MyClient() {}
            static public void main(String argv[])
                try
                    Socket s = new Socket("127.0.0.1", 50080);
                    OutputStream os = s.getOutputStream();
                    String text = "text1\r\ntext2";
                    os.write(text.getBytes());
                    os.flush();  // We know it was sent.
                    // Important!  The socket remains open!
                    while(true)
                        Thread.currentThread().sleep(60 * 1000);
                catch(Throwable e)
                    e.printStackTrace();
    //----------- Server
        import java.net.*;
        public class MyServer implements Runnable
            Socket s;
            public MyServer(Socket s)
                this.s = s;
            static public void main(String argv[])
                try
                    ServerSocket ss=new ServerSocket(50080);
                    while(true)
                        Socket s=ss.accept();
                        Thread t = new Thread(new MyServer(s));
                        t.start();
                catch(Throwable e)
                    e.printStackTrace();
            public void run()
                try
                    System.out.println("***socket start");
                    java.io.InputStream ins=s.getInputStream();
                    // Case 1: Does NOT work
                    int j;
                    while((j=ins.read())!=-1)
                        System.out.write(j);
                    // Case 3: Does work
                    while (true)
                        int len = ins.available();
                        if ((len < 0) || s.isClosed()) break;
                        byte b[] = new byte[len];
                        ins.read(b);
                        for (int i=0; i < len; i++)
                            System.out.print((char)b);
    // Case 3: Does work
    while (true)
    int len = ins.available();
    if ((len < 0) || s.isClosed()) break;
    for (int i=0; i < len; i++)
    int b = ins.read();
    System.out.print((char)b);
    System.out.println("***socket end");
    catch(Throwable e)
    e.printStackTrace();

    System.out is line buffered. (I can only hope that I might have noticed this myself if I had been smart enough to use the same output method.)
    Ok so it isn't a socket problem. But I still don't see anything that documents the behavior.
    System.out is documented as a java.io.PrintStream. And that is actually the class that implements it.
    Nothing in the documentation for PrintStream, the methods, the FilterOutputStream or even OutputStream would suggest the different behavior.
    C works the same way; this never prints "world" on most systems:C works that way because of the way file descriptors work and the way that the buffers for those are handled. And how it works is undefined, a C implementation is allowed to handle it anyway it wants.
    But this Java and not C. That means at a minimum that the behavior must be the same on all OSs. But given that the behavior is not documented then it could be that it is left to the implementation of the C library that the java io library is built upon. And that is not a good thing (in terms of normal java.)
    The following demonstrates the behavior using the two output methods...
          String text = "text1\r\ntext2";
          byte[] b = text.getBytes();
          System.out.println("--- print using print() sleep for 10 secs after");
          for (int i=0; i < b.length; i++)
             System.out.print((char)b);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- print using write() sleep for 10 secs after");
    for (int i=0; i < b.length; i++)
    System.out.write((int)b[i]);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- done");

  • Bug with InputStream.read after BufferedReader.readLine in a Thread ?

    I just found something strange when reading bytes on a socket after reading lines.
    I'll show you an example :
    In this example, when a connexion is established, I launch a thread where a single line of String then 3 bytes are read from the socket. I use BufferedReader.readLine for the String line then just InputStream.read to read the 3 bytes.
    The results are quite random. Sometimes it works, sometimes not (most times it doesn't)... it seems to always work under linux (but haven't tested it as many times than on windows). Most of the time the program is stuck on the "socket.getInputStream().read(bytes);" line with 0 bytes available. I tried to do the same thing outside of a thread, I thought it worked better beaucause I was able to run it without any problem but it doesn't work anymore when I test it again.
    I can't say if I'm doing something wrong or if it's a java bug (I've got JDK 1.6.0_03-b05).
    Can you please have a look a this little example and maybe test it and let me know if it works or not. I tried to code my own readLine function and it seems to work with it but I'd like to know if it's a bug or what. Thank you.
    Server side :
    import java.io.*;
    import java.net.*;
    public class testServer extends Thread {
         private Socket socket;
         public testServer(Socket testSocket)
              socket = testSocket;
         public void readData() throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String str;
              str = br.readLine();
              System.out.println(str);
              System.out.println("Bytes available : " + socket.getInputStream().available());
                    //Try to read the bytes
                    byte[] bytes = new byte[3];
                    //STOPS THERE UNDER WINDOWS, BUT WORKS WITH LINUX
              socket.getInputStream().read(bytes);
                    //Simple "ack" to say to the client that he can close the connexion
              socket.getOutputStream().write(0);
              socket.getOutputStream().flush();
                    //Print the bytes values
              for(byte value : bytes)
                   System.out.println(value);
         public void run()
              try {
                   readData();
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              try {
                   ServerSocket welcomeSocket = new ServerSocket(3333);
                   while(true)
                        new testServer(welcomeSocket.accept()).start();
              } catch (Exception e) {
                   e.printStackTrace();
    }client side :
    import java.io.*;
    import java.net.*;
    public class testClient {
         public static void main(String[] args) {
              try {
                            //Some test values
                   byte[] testValues = new byte[]{1,2,3};
                   Socket socket = new Socket(InetAddress.getLocalHost(), 3333);
                            //Send the line through the socket
                   BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                   bw.write("HELLO WORLD\r\n");
                   bw.flush();
                            //then the bytes
                   socket.getOutputStream().write(testValues);
                   socket.getOutputStream().flush();
                            //Just waits for the server's ack to close the connexion
                   socket.getInputStream().read();
                   socket.close();
              } catch (Exception e) {
                   e.printStackTrace();
    }

    It's your bug.
    When you create a BufferedReader and ask it to read a line, the first thing it does is to read a whole buffer full of data (hence the name of the class) from its underlying input stream. That's probably about 4000 characters or something like that. It stores that internally and then starts doling it out in response to calls to readLine() and so on.
    Then when you go back to reading from the underlying input stream, those 4000 or so characters are already gone from it. You have no access to the data the BufferedReader is hanging on to this way. All you can do is to start reading at the point after that whole buffer, which is not what you want.

  • Why can't InputStream.read() be interrupted?

    I have a native application that launches a java application. To allow for the communication between the two applications, the native app launches the java app with stdin and stdout redirected to a file handles. The Java application creates a thread to read from System.in. Everything works great -- UNTIL . . .
    . . . the native app closes the communcation handles and exits, leaving the java application blocking on the InputStream.read().
    My question is why doesn't the blocking InputStream.read() get interrupted when the communcation handle in the native app closes? This appears to be a BUG in Java. I would expect to get an exception or error on the read when the handle on the other sides exits.
    My ideas to work around this would include changing the IPC communcation to a network protocol like sockets, or MMF. However, redirecting stdin and stdout seemed to be the simpliest IPC. Any other ideas or suggestions?
    Cheers,
    Kyley

    Thanks for all your replies. Hearing others express the same idea that it should work the way that I had thought made me revisit how the native application was launching the application and how the handles were redirected.
    After getting things working on UNIX (Sun Solaris), I looked again at the code (which I didn't write) that launched the java application on Windows. After rewriting the code, the original code wasn't duplicating stdin & stdout and closing one of the original handles. Once that was done properly, AMAZINGLY everything worked as I had intended it to work.
    Thanks again for the time to reply.
    Kyley

  • I add a timeout for InputStream read().

    I am looking for a timeout for InputStream read() since Java doesn't support it. I use a Timer class to handle the timeout value and put the InputStream.read() into another thread. When the time is up, the Timer object will stop the thread of reading. What do you think about this solution? Do you have any other better solution?
    thanks

    and any ideas on how to stop this blocking read() method from an InputStream (Java 5)???? When googling on this topic I find an incredible amount of questions on this subject BUT no solutions. What to do?? I'm a little bit affraid it comes down to hacking the JVM finding the Thread in some memory block and removing it with brute force.
    hmmm when I think of it, it's really driving my crazy.... the only thing I can think of is throwing my PC out of the window and buy a new one. Unfortunately there's no budget for that it will cost to many PCs :-)
    Edited by: R_e_n_s on Jun 3, 2008 6:45 AM

  • Closing InputStream / InputStream Reader

    Hello,
    I need suggestion regarding closing InputStream / InputStream Reader.
    If I have these two lines of code below:
    InputStream inStream = ...;
    InputStreamReader inStreamReader = new InputStreamReader (inStream );Is it necessary to do both:
    inStream.close();
    inStreamReader.close();I can't confirm but some people say that it is necessary only to do inStreamReader.close() and inStreamReader#close will do inStream#close as well.
    Could somebody please advise?
    Thanks.

    read the close method on inputStream
    [url=http://java.sun.com/j2se/1.5.0/docs/api/java/io/I
    nputStream.html#close()]here. its kind offunny.
    Interesting,
    I've never noticed that before.
    So, InputStream#close method is not necessary at all, isn't it?
    Thanks for the lead Brigand,

  • Socket stream read() method blocks

    Hi,
    client connects to our server socket.
    our thread blocks for getting the input data from the client, but the client is closed with out sending any data.
    so our thread is blocked for the input data for ever.
    how could our application will know that the client socket is closed.
    once we got some data from the client , after that client is closed then we can know that the client is closed because read() method will return -1 .
    Thanks ,
    S P K S.

    yes you are right when the client sent some data then after some time connection got closed , then our read() will return -1It doesn't matter whether the client has sent data or not. If the client closes the connection properly your read will return -1.
    but here my problem is just client is connected , he didn't send a bit of data , connection got closed ,in that case read method is still waiting for the input it is not returning any thing and not throwing any exception.If the connection is dropped abortively a read can block forever. Your defence against this is to use a read timeout of say 60 seconds. or whatever is appropriate for your application. See Socket.setSoTimeout().

  • SerialPort: inputStream.read blocks, never return -1

    I use javax.comm package to transfer files between two virtual com ports (looped)
    Send a file from com3, and receive file from com4, but at reciever side, inputStream.read(buffer) never return eveb though I close the outputstream at the sender.
    Here is code:
    is: serialPort.getInputStream();
    os: serialPort.getOutputStream();
    //sender:
    //fis: FileInputStream
    try {
         int i =0;
         while ((counter=fis.read(buffer)) > 0 ){
              fileSize += counter;
              debugInfo(i + ": "+counter + "bytes read");
              os.write(buffer,0,counter);
              i++;
         debugInfo(fileSize + " bytes read totally");
         os.flush();
         fis.close();
         //close os when no file need transfering
         os.close();
    } catch(IOException e) {
         e.printStackTrace();
    }file receiver
    fos: FileOutStream
    try {
         int i =0;
         while ((counter=is.read(buffer)) >0){ //blocks and never return
              counter=is.read(buffer);
               fileSize += counter;
               debugInfo(i + ": "+ counter + " bytes read");
               fos.write(buffer,0, counter);
               i++;
    debugInfo(fileSize + " bytes write totally");
    fos.flush();
    fos.close();
    debugInfo("fos closed");
    is.close();
    } catch(IOException error) {
         error.printStackTrace();
    }Anything I have done wrong? or anything better solution? Thanks

    oops, sorry for copied wrong codes. Thanks for your remind. The second read was used with while (is.availble()), when I post, I forgot to remove it. You are right, if I have read twice, I will not even get the right file, since I only write every second buffer in.
    Here I update the receiver, I can get the whole file correctly, but can't get EOF.
    //file receiver
    //fos: FileOutStream
    try {
         while ((counter=is.read(buffer)) >0){ //blocks and never return
              fileSize += counter;
               fos.write(buffer,0, counter);
    fos.flush();
    fos.close();
    is.close();
    } catch(IOException error) {
         error.printStackTrace();
    }

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • How to avoid thread stops ? ( when try to read sockets inputstream ...)

    Hi ,
    When I try to call :
    Socket sok=new Socket (adres,poort);
    the thread looks to stop...
    How to avoid this ?
    Thx for tip etc !

    Take a look at NIO:
    http://www.google.com/search?num=100&hl=en&c2coff=1&q=non-blocking+java+socket

  • Block again after InputStream.read() return -1

    Hello,
    I've got the following problem: I call read() on my InputStream object until the function return -1. The read() call is done in a loop. After that i start processing the received data. The socket is not closed and i want to start a blocking read() call again. But this doesn't work. Instead the read() return -1 again and again..... This make sense to me because there are actually no data, but i expected that read() is blocking again.
    Does anyone know this problem?
    By the way: Can i change my screen name. I typed in some stupid stuff as I think i could change is later.
    Thanks
    Christian

    read() returning -1 means that the other end has closed the connection. All you can do is close yours. There will never be any more data so there is nothing for it to block for.

  • Gunzip a Socket InputStream

    Hi all,
    I have a little problem with the GZIPInputStream class. In my application I extend the BufferedInputStream to read the InputStream from a Socket.
    If the content-encoding of the HTML response if gzip, I want to gunzip it, but I don't know how I must do!
    I create a new GZIPInputStream object and I passed it the InputStream (I initialize the class calling super(socket.getInputStream()) where socket is a constructor parameter). The code of my function is:
    public String gunzip() {
      try {...
         GZIPInputStream zipin = new GZIPInputStream(super.in);
      catch(...){...}
    }But, when I try to create the Object I get a java.net.SocketTimeoutException: Read timed outand I don't understand why?!?!
    Please help!
    Ciao

    OK,
    I have the complete compressed file in a String, but the GZIPInputStream wants an InputStream, and I don't know how I can pass the file to GZIPInputStream constructor.

  • Socket DataInputStream read SocketTimeException

    Hi all,
    I got a socket client/server, but while read(), the client do heartbeat every 1/4 second, and following is the heartbeat's mainly code.
    The question is there will be a Timeout exception intermittently. I mean it during 100 times heartbeats, there will 1~2 times failed to read(), but the followed thrid can successfully read from the inputStream.
    socketClient.setSoTimeout(10*1000); // timeout 10s
    DataInputStream input = socketClient.getInputStream();
              byte[] outputData = null;
              try {
                   byte[] outputDataTemp = new byte[252];
                   COSLogger.doInfo("ModbusRequest", "execute", "input.available() = "+input.available());     // why available() always is 0?
                   int size = input.read(outputDataTemp);// SocketTimeoutException occured here
                   if (size <= 0) {
                        throw new Jnior310Exception("Invalid zero-length response from jnior.");
                   outputData = new byte[size];
                   for (int i = 0; (i < size); i++) {
                        outputData[i] = outputDataTemp;
              } catch (IOException e) {
                   throw new Jnior310Exception("IOException on read: " + e);
              }Any reply is appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    than wrote:
    Please note in most time it read correctly, in this situation the weird thing is input.available=0, but the after sucussful read(), the size=10Returning 0 is the default behavior of the available function of a DataInputStream. The API for DataInputStream says :
    Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
    This method returns the result of in.available(). where in is an InputStream. The API for InputStream says :
    The available method for class InputStream always returns 0I only know this because I recently made that mistake as well...but the available function is basiclly useless in this instance (Unless you're looking for a confusing way to initialize a for loop)...

  • Socket buffered read yields corrupt data

    While trying to read from a socket, the data gets corrupted:
    First, from telnet, I send the length of the data: 12<enter>
    Then I send the data: this is some data
    The server only displays part of the data:
    �� = some unprintable character (I can't even copy it from the console)
    examples:
    SEND 11<enter>
    SEND this is a test for
    System.out.println yields: "this is &#8234;������"
    SEND 11<enter>
    SEND this is a test for socket data
    System.out.println yields: "this is &#8234;������"
    SEND 13<enter>
    SEND this is a test for socket data
    System.out.println yields: "this is &#8234;����������"
    SEND 13<enter>
    SEND this is a test for socket data, yes, for sockets
    System.out.println yields: "this is &#8234;����������"
    SEND 20<enter>
    SEND this is a test for socket data, yes, for sockets
    System.out.println yields: "this is ������������������������"
    s_out = new PrintWriter(s_socket.getOutputStream(), true);
    s_in = new BufferedReader(new InputStreamReader(s_socket.getInputStream()));
    AProtocol proto = new AProtocol();
    int data_length = 0;
    while (proto.state != STATUS_GOODBYE){
         switch (proto.state) {
         case STATUS_WAITING_LENGTH :
              inputLine = s_in.readLine();
              s_out.println(proto.processInput(inputLine));
              if (proto.state == STATUS_WAITING_DATA){
                   data_length = Integer.parseInt(inputLine.trim());     
              break;
                                  case STATUS_WAITING_DATA :
              inarray = new char[data_length];
              if ((count = s_in.read(inarray,0,data_length)) >= 0){
                   inputLine = String.valueOf(inarray);
                   proto.processInput(inputLine);
                   if (proto.state == STATUS_WAITING_LENGTH){
                        System.out.println("*" + inputLine + "*");
              break;
    }

    It looks like you're writing bytes, but reading them as Java characters (e.g., Unicode).

Maybe you are looking for

  • XI Debugging tool in the Configuration -Integration Builder

    Hello to XI Experts,  I an testing the XI Debugging tool in the Configuration -Integration Builder Menu Path is :  Tool->Test Configuration.  It is simple Idoc to Flat File Mapping and it gets executed . However when I test it using the Test Configur

  • Help with email attachment of keynote presentation

    Hi, I have just spent a significant amount of time doing a presentation on keynote. I am trying to email it to myself to access it tommorrow. However everytime I attempt to do it, it states that safari can not open the page. Any advice! I thank you i

  • Cost center planning data-Plan Variable Costs in Object Currency

    Dear All: I have copied a standard planning layout and for the field, 'Planned Fixed Cost' and 'Planned Variable Cost', I have selected 'Plan Variable Costs in Object Currency' and 'Plan Fixed Costs in Object Currency' as the Key Figure. I am doing t

  • Licensing Error: 5

    I am trying to install my Creative Suite 4 on my new iMac and have received the following error: "Licensing for this product has stopped working." Error: 5 Is there some reason why CS4 would be incompatible with new Apple software? Thanks for your he

  • Issue with CL_WDABAP_FLIGHT_MODEL

    I am new to Web Dynpro and abap objects. I am practising with the examples given at SDN for the beginners.In the  Tutorial 4 - Display Bookings for Selected Flights  and at step --Implement supply method GET_BOOKINGS which fills the node BOOKINGS wit