简体   繁体   中英

Multi Bit TCP Request in Java

I am trying to make a tcp request in Java to a existing TCP server that is already available. the interface specification is:

Field           Length      Type
Length          2 bytes     16-bits binary
Message ID      1 byte      8-bits binary
MSGTYPE         1 byte      8-bits binary
Variable1       4 bytes     32-bits binary
Variable2       30 bytes    ASCII
Variable3       1 byte      8-bits binary

I understand how to convert a String to Binary using BigInteger.

String testing = "Test Binary";
byte[] bytes = testing.getBytes();
BigInteger bi = new BigInteger(bytes);
System.out.println(bi.toString(2));

My Understanding is that if i wanted to make a TCP request i would first

  1. need to convert each binary to a string
  2. append the values to a StringBuffer.

Unfortunately my understanding is limited so i wanted some advice on creating the TCP request correctly.

I wouldn't use String (as you have binary data), StringBuffer (ever), or BigInteger (as it not what its designed for).

Assuming you have a Big Endian data stream I would use DataOutputStream

DataOutptuStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

out.writeShort(length);
out.write(messageId);
out.write(msgtype);
out.write((var1+"\0\0\0\0").substring(0, 4).getBytes("ISO-8859-1"));
out.write(var2.getBytes("ISO-8859-1"));
out.write(var2);

out.flush(); // optionally.

If you have a little endian protocol, you need to use ByteBuffer in which case I would use a blocking NIO SocketChannel.

BTW I would use ISO-8859-1 (8-bit bytes) rather than US-ASCII (7-bit bytes)

You are going into the wrong direction. The fact that the message specification states that, for example, first field is a 16 bit binary doesn't mean that you will send a binary string. You will just send an (unsigned?) 16 bit number which will be, as a matter of fact, codified in binary since it's internal representation can just be that one.

When writing onto a socket through an DataOutputStream like in

int value = 123456;
out.writeInt(value);

you are already writing it in binary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM