Solved

Scope of thread?

Posted on 2004-04-29
15
308 Views
Last Modified: 2010-04-16
Can anyone tell me what is the scope of a thread and socket...  I am encountering a problem where data returned from my server application is being dropped midway through it. I think maybe the problem is related to garbage collection and object scope.

The following code will listen for a message from a client, then in the ReadWriteSocketThread, it reads the given socket(within run()) and responds with lots of data (3000+ bytes) using the socket.getOutputStream()...  It flushes the stream at every 180 bytes or so. The problem is that the client only receives events for 1 to n of these "flushes"... and sometimes it receives the entire stream.

public class MyServerApplication
{
  public MyServerApplication()
  {
    try
    {
        int listenPort = 800;
        ServerSocket serverSocket = new ServerSocket(listenPort);
        // For each new connection start a thread to handle it
        while (true)
        {
            Socket s = serverSocket.accept();
            System.out.println("Creating a local thread");
            ReadWriteSocketThread thread = new ReadWriteSocketThread (s);
            thread.start();
        }
    }
    catch (Exception e)
    {
        System.out.println("Exception");
        e.printStackTrace();
    }
  }

  public static void main (String args[])
  {
    MyServerApplication server = new MyServerApplication();
  }
}


public class ReadWriteSocketThread extends Thread
{
 public void run()
 {
  try
  {
    int b;
    int len;
    byte[] bt = new byte[4];
    String startMessage = new String ("*START*");

    BufferedInputStream in = new BufferedInputStream(mySocket.getInputStream());
    StringBuffer sb = new StringBuffer();

    boolean isValid = false;
    if (in.read(bt, 0, 4) == 4)
    {
        len = bt[0] * 256 + bt[1];
        System.out.println("Length of string: " + len);
        for (int i = 0; i < len; i ++)
        {
            b = in.read();
            if (b == -1)
                break;
            sb.append((char)b);
        }
        System.out.println("String: " + sb.toString());
        if (sb.toString().equals(startMessage))
        {
            isValid = true;
        }
    }
    if (isValid && in.read(bt, 0, 4) == 4)
    {
        sb.setLength(0);
        len = bt[0] * 256 + bt[1];
        System.out.println("Length of string: " + len);
        for (int i = 0; i < len; i ++)
        {
            b = in.read();
            if (b == -1)
                break;
            sb.append((char)b);
        }
        System.out.println("String: " + sb.toString());
    }
    if (isValid)
    {
        if (in.read(bt, 0, 4) == 4)
        {
            len = bt[0] * 256 + bt[1];
            if (len != 4)
            {
                ErrorLog eLog = new ErrorLog(m_Config);
                eLog.log("Error reading from socket: Message end tag was not found.");
            }
        }
    }

    System.out.println("Received: " + sb.toString());

    // SEND BACK A RESPONSE IN PIECES:
    Responder makeAnswer = new Responder(sb.toString());
    BufferedOutputStream out = new BufferedOutputStream(mySocket.getOutputStream());

    int numResponses = makeAnswer.getNumResponses();
    System.out.println("NumResponses: " + numResponses);

    // numResponses is typically between 15 and 18:
    for (int i = 0; i < numResponses; i ++)
    {
        // response is typically 180 bytes on a good day:
        String response = makeAnswer.getResponse(i);
        //System.out.println ("response: "+ response);
        //System.out.println ("length: "+ response.length());

        int lenOut = response.length()+2;
        out.write(lenOut / 256);
        out.write(lenOut);  
        for (int j=0;j<response.length();j++)
            out.write((byte)(response.charAt(j)));
        out.write(0);
        out.flush();
    }
                        
    out.close();
                  
    in.close();
    m_oSocket.close();  
  } catch (IOException e) {
    //System.out.println ("IOException in Thread");
    ErrorLog eLog = new ErrorLog(m_Config);
    eLog.log("Error reading from socket: "+e.getMessage());
  }
 }
}

0
Comment
Question by:bganoush
  • 6
  • 5
  • 3
  • +1
15 Comments
 
LVL 23

Expert Comment

by:rama_krishna580
Comment Utility
0
 
LVL 14

Assisted Solution

by:Tommy Braas
Tommy Braas earned 200 total points
Comment Utility
First of all, don't call flush that often. There is no need and it usually decreases performance. Try that first.
0
 
LVL 22

Accepted Solution

by:
NovaDenizen earned 300 total points
Comment Utility
Here is an important and subtle problem:
    byte[] bt = new byte[4];
....
        len = bt[0] * 256 + bt[1];

Sit down for this one.

byte is a SIGNED data type!  yes!  really!  I'm not joking!  It can only represent values from -128 to +127!  really!  I mean it!

If you read a byte 0xf5 (decimal 245) from a file, then multiply the byte by the integer 10, you don't get 245*10=2450.  Instead, you get -11*10==-110!  Since byte is a signed data type, 0xf5 has the value -11.  

How do you cope with this?  Well, every time you want to treat a byte like an unsiged value from 0-255, you have to do a &0xff to it.  So, your len statement above should look like this:

len = (bt[0] & 0xff)*256 + (bt[1] & 0xff);

Isn't that annoying!
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
NovaDenizen, I think you posted to the wrong thread. And the fact that byte is a signed datatype is not exactly a revelation!
0
 
LVL 22

Expert Comment

by:NovaDenizen
Comment Utility
oops.
0
 
LVL 22

Expert Comment

by:NovaDenizen
Comment Utility
No, this was the right thread, and this is a serious problem in his code.  This is how he was calculating the number of bytes to read.  

When length < 32768 and (length % 256) >= 128, this bug would cause premature ending of the loop that is reading in data one character at a a time.

When length < 32768 and (length % 256) < 128, there would not be any obvious bug, and the complete buffer would be read.

when length >= 32768, the length would always be negative, and no data would be read.
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
>> len = bt[0] * 256 + bt[1];
There is no problem here. len is an integer and all the byte values are automatically promoted to integers.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
>>  all the byte values are automatically promoted to integers.
Due to the presence of the 256 integer literal.
0
 
LVL 22

Expert Comment

by:NovaDenizen
Comment Utility
Yes, and they are promoted to integers in the range -128 to +127 because they are a signed data type.
0
 
LVL 22

Expert Comment

by:NovaDenizen
Comment Utility
Please just try it and see!

class testclass {
public static void main(String args[]) {
     byte b = 140;
     int i1, i2;
     i1 = b;
     i2 = b & 0xff;
     System.out.println("i1 is " + i1 + ", i2 is " + i2 + "\n");
}
}
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
>>  Yes, and they are promoted to integers in the range -128 to +127 because they are a signed data type.
You are absolutely right, I misinterpreted your post.

If you want to write the *START* message and the length of the whole message, please use DataInput- and DataOutputStreams. Another option is to send the *START* message and then a serialized String using an ObjectOutput- ObjectInputStream pair.
0
 

Author Comment

by:bganoush
Comment Utility

Now another question... How many times do I have to hit myself over the head before it starts hurting???

Ok,  granted, the byte thing was stupid but in this particular code I am testing, the packets are all less than 128... although I could be wrong...

In any case, I'm going to test this first thing tomorrow morning when I get back to work...

Thanks for the input guys!

-- Bubba
0
 

Author Comment

by:bganoush
Comment Utility

Ok, I fixed that particular bug but that didn't solve my problem. I did however re-write some of the code after looking at that byte thing and the DataOutput classes...  And the bug went away.

Also, I verified that my packets were never larger than 90 or so bytes long in my test code although my final code will have to take the length more seriously.

-- Thanks again!
0
 

Author Comment

by:bganoush
Comment Utility
Actually,

I also found this problem with the code:

        int lenOut = response.length()+2;
        out.write(lenOut / 256);
        out.write(lenOut);  
        for (int j=0;j<response.length();j++)
            out.write((byte)(response.charAt(j)));
        out.write(0);                     <---------------------- bug here
        out.flush();

Notice that when the response is returned, a terminating null byte is added to the end of the output stream. So when I read the data, it gets out of phase by one byte...  For instance, when reading the data, I read the length word, then the string which is exactly that size but then I assume that this is followed by the next length word (this is in the client code, not shown here). In any case, since the data does not comply with my protocol, I drop the data and wait for the next packet...

In my rewrite, I do not write out the null byte at the end.

-- Bubba
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
=-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now