I have an app that reads bytes from a socket using a BufferedInputStream. These bytes are stored in a byte[] buffer.
Now, unless I output the bytes I read to the System.out stream with my debug() method after reading them , my app simply does not work, I get ArrayIndexOutOfBounds exceptions while reading into the buffer, etc.
The connect, readBytes, debug and part of the run() methods are shown below. The bytes are read this way because of the way the packets are sent (2 bytes for packet size, then rest of packet).
Using java Syntax Highlighting
- public void connect(String username, String password) {
- this.username = username;
- this.password = password;
- try {
- if (!runThread)
- return;
- Socket s = new Socket("cs.xfire.com", 25999);
- in = new BufferedInputStream(s.getInputStream(), 16384);
- out = new DataOutputStream(s.getOutputStream());
- login();
- } catch (IOException ioe) {
- disconnect();
- }
- }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
Using java Syntax Highlighting
- private void readBytes() {
- try {
- int low = in.read(), high = in.read();
- int len = (0x00 | low | (high << <img src="http://www.anddev.org/images/smilies/cool.png" alt="8)" title="Cool" />) - 2;
- buffer = new byte[len];
- in.read(buffer, 0, len);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- disconnect();
- } catch (NegativeArraySizeException nase) {
- buffer = new byte[] { 0 };
- }
- }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
Using java Syntax Highlighting
- private static void debug(byte[] bs) {
- for (byte b : bs) {
- System.out.print(String.format("%02x", b) + " ");
- }
- System.out.println();
- }
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
Using java Syntax Highlighting
- public void run() {
- setName("Xfire Reader Thread");
- while(runThread) {
- readBytes();
- debug(buffer);
- switch(buffer[0] & 0xFF) {
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
Commenting out 'debug(buffer);' in the last code snippet will cause the app to malfunction.


