[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Scope of thread?

Posted on 2004-04-29
15
Medium Priority
?
320 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 3
  • +1
15 Comments
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10951371
0
 
LVL 14

Assisted Solution

by:Tommy Braas
Tommy Braas earned 800 total points
ID: 10951617
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 1200 total points
ID: 10952708
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10952992
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
ID: 10953007
oops.
0
 
LVL 22

Expert Comment

by:NovaDenizen
ID: 10953055
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
ID: 10953137
>> 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
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10953145
>>  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
ID: 10953195
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
ID: 10953209
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
ID: 10953401
>>  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
ID: 10955098

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
ID: 10958615

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
ID: 10958697
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
ID: 10963940
=-)
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
This video teaches viewers about errors in exception handling.
Suggested Courses

649 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