• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Socket  RSS feed

 
Marina JOSEPH
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
read the length of the data into 4 byte, this is to make it platform independent.
In this method how to change to read the length of the data into 2 byte,
static final byte[] Read(BufferedInputStream inStream) throws Exception
{

byte[] pSize = new byte[4];
int nTotal = 0;
int nRead = 0;
while(nTotal<4)
{
nRead = inStream.read(pSize,nTotal,4-nTotal);
if(nRead<0) break;
nTotal += nRead;
}

int nSize = (pSize[0]&0x000000ff)|((pSize[1]&0x000000ff)<<8)|((pSize[2]&0x000000ff)<<16)|((pSize[3]&0x000000ff)<<24);

if(nRead<0||nSize<0) throw new Exception("Invalid input data");

// then read the actual data into a byte array

if(nSize==0) return "".getBytes();

byte[] pData = new byte[nSize];

nTotal = 0;

nRead = 0;
while(nTotal<nSize)
{
nRead = inStream.read(pData,nTotal,nSize-nTotal);

if(nRead<0) break;
nTotal += nRead;
}
if(nRead<0) throw new Exception("Invalid input data");
return pData;
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!