I\'m writing a java socket program to read data from server, I\'ve no control to server, below is protocol agreed,
According to the specification you must build a packet shaped in the following way
| 2 | 2 | N ........ |
Now this could be quite easy and there are multiple ways to do it, I suggest you one:
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
static byte[] buildPacket(int magicNumber, String payload) throws UnsupportedEncodingException
{
// 4 bytes for header + payload
ByteBuffer buffer = ByteBuffer.allocate(2 + 2 + payload.length());
// we set that we want big endian numbers
buffer.order(ByteOrder.BIG_ENDIAN);
buffer.putShort((short)magicNumber);
buffer.putShort((short)payload.length());
buffer.put(payload.getBytes("US-ASCII"));
return buffer.array();
}
public static void main (String[] args) throws java.lang.Exception
{
try
{
byte[] bytes = buildPacket(0xFF10, "foobar");
for (byte b : bytes)
System.out.printf("0x%02X ", b);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Mind that if you declare the method to accept a short
magic number directly, you won't be able to pass a literal magic number > 32767
because short
is signed in Java.
Watch out for the big endinanness!
DataxxxStream - although it is quite handy - does not offer a full support for both little and big endian numbers and arbitrary String encodings.
See my post at How to Read Byte Stream from Socket
Use a DataOutputStream
around a BufferedOutputStream
around the `Socket.getOutputStream(). Then you can use:
writeShort()
for the magic numberwriteShort()
for the length wordwrite()
for the payload.Similarly you can use DataInputStream
and the corresponding readXXX()
methods to read the response.
NB You are writing to a socket here, not a server socket.