[英]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. 我正在尝试以Java向现有TCP服务器发出tcp请求。 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. 我了解如何使用BigInteger将String转换为Binary。
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 我的理解是,如果我想发出TCP请求,我会先
Unfortunately my understanding is limited so i wanted some advice on creating the TCP request correctly. 不幸的是,我的理解是有限的,所以我想要一些有关正确创建TCP请求的建议。
I wouldn't use String (as you have binary data), StringBuffer (ever), or BigInteger (as it not what its designed for). 我不会使用String(因为您有二进制数据),StringBuffer(曾经)或BigInteger(因为它不是为它设计的)。
Assuming you have a Big Endian data stream I would use DataOutputStream 假设您有一个Big Endian数据流,我将使用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. 如果您有一点端序协议,则需要使用ByteBuffer,在这种情况下,我将使用阻塞NIO SocketChannel。
BTW I would use ISO-8859-1
(8-bit bytes) rather than US-ASCII
(7-bit bytes) 顺便说一句,我会使用ISO-8859-1
(8位字节)而不是US-ASCII
(7位字节)
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. 消息规范指出例如第一个字段是16位二进制文件这一事实并不意味着您将发送二进制字符串。 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. 您将只发送一个(无符号?)16位数字,实际上,该数字将被编码为二进制,因为它的内部表示形式可能就是那个。
When writing onto a socket through an DataOutputStream
like in 当通过DataOutputStream
写入套接字时,例如
int value = 123456;
out.writeInt(value);
you are already writing it in binary. 您已经用二进制文件编写了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.