I am putting together a fairly simple server that listens for a connection then creates this thread - textbook Java code - then accepts data on that connection.
I am following a protocol that the manufacturer has laid out for start of message(0xfd) and EOM( 0xfe) as below. I then simply populate a byte array with using a bytecounter.
I think this is the simplest doing so, and it seems to work fine. Is there any possible problem with taking this approach? I want to be sure using a bytecounter
with an array is acceptable. I can't see anyway that bytecounter
could get out of sync or anything like that. I like to keeps things simple. Is there anything wrong with this code with regard to stuffing the 'inbyte[]' array?
public void run() {
try {
boolean socketalive = true;
MSG_ID = 0;
disIn = new DataInputStream( in );
disOut = new DataOutputStream ( out );
String msg = null;
StringBuilder hexforlog;
byte[] c ;
int i = 0;
int bytecounter = 0;
byte[] inbyte ;
while( true ){
i = 0;
bytecounter = 0;
inbyte = new byte[1024];
byte b ;
try{
/* read from network until end of message byte is received */
while( ( b = disIn.readByte() ) != (byte)0xfe ){
/* checking for start of message */
if( b == (byte)0xfd ){
inbyte = new byte[1024];
inbyte[0] = b;
bytecounter = 1;
}
else {
inbyte[bytecounter] = b;
bytecounter++;
}
}
}catch ( java.io.EOFException ioef ){
System.out.println("EOF recieved bytes" );
break;
}
/*test for link verification */
if( bytecounter == 15 ){
byte SOURCEbyte = inbyte[2];
byte DESTbyte = inbyte[3];
/* swap bytes per protocol */
inbyte[2] = (byte)DESTbyte;
inbyte[3] = (byte)SOURCEbyte;
disOut.write( java.util.Arrays.copyOfRange(inbyte,0,16) );
disOut.flush();
}
/* process the data as per manufacturer spec */
else if( bytecounter> 16 ){
arrayindex = 12;
int SOM = inbyte[0];
int CLASS = inbyte[1];
int SOURCE = inbyte[2];
int DEST = inbyte[3];
int MSG_PRG_NUMBER = inbyte[4];
int SPARE1 = inbyte[5];
int SPARE2 = inbyte[6];
int SPARE3 = inbyte[7];
LENGTH = twoBytesToInt( new byte[] { inbyte[8], inbyte[9] } );
NUM_MSG = twoBytesToInt( new byte[] { inbyte[10], inbyte[11] } );
System.out.println("LENGTH: " + LENGTH + " NUM_MSG: " + NUM_MSG );
System.out.println("Setting NUM_MSG to 1" );
NUM_MSG = 1;
for ( int j=0; j<NUM_MSG; j++ ) {
MSG_ID = twoBytesToInt( new byte[] { inbyte[arrayindex],
inbyte[arrayindex+1] } );
System.out.println("MSG_ID: " + MSG_ID );
MSG_LENGTH =twoBytesToInt( new byte[] { inbyte[arrayindex+2],
inbyte[arrayindex+3] } );
System.out.println("MSG_LENGTH: " + MSG_LENGTH );
arrayindex = arrayindex+4; //first go around 15
currentarray = java.util.Arrays.copyOfRange(
inbyte, arrayindex, arrayindex+MSG_LENGTH+1);
arrayindex = arrayindex+MSG_LENGTH ;
//process messages
if(MSG_ID == 50){
processMessage50( currentarray );
}
else if(MSG_ID == 70){
processMessage70( currentarray);
}
}
}
}
disIn.close();
disOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}