读出并通过套接字写字节的数据包 [英] Read and Write Bytes data packet via socket
问题描述
我想通过插座的Android设备连接到外部设备。套接字连接到成功的外部设备。
I want to connect Android Device to external device via Socket. Socket Connect to external device successfully.
现在,如果来自外部设备的任何数据需要再发送一个字节的数据包数据的请求,插座下面秩序。如果外部设备接收的数据正确,那么响应发送字节的数据。
Now if any data require from external device then send request of byte packet data to socket below order. if external device receive data correct then send byte data in response.
参数:方法名(1字节),payloadlength(2字节),有效载荷(2字节)
Parameters : methodname(1 byte), payloadlength(2 byte), payload(2 byte).
现在我的code是...
Now My Code is...
Socket socket = new Socket("local exteranl device ip", 5000);
if(socket.isConnected()) {
int methodname = 5;
int payload = 2151;
int payloadLength = 2;
ByteBuffer buffer = ByteBuffer.allocate(3 + payloadLength); // 3 = for method name + length
buffer.order(ByteOrder.BIG_ENDIAN); // Just to be explicit
buffer.put((byte) methodname);
buffer.putShort((short) payloadLength);
buffer.putShort((short) payload);
buffer.rewind();
byte[] result = new byte[buffer.capacity()]; // Could also use result = buffer.array();
buffer.get(result);
DataOutputStream classOUTstream = new DataOutputStream(socket.getOutputStream());
// socket is already connected
classOUTstream.write(result);
classOUTstream.flush();
InputStream stream = socket.getInputStream();
byte[] data = new byte[100];
int count = stream.read(data);
}
以上code是Android的,我只知道基本的Java概念。我得到的 -1结果的数量。
任何一个可以请建议我还是告诉我,我错了吗?
can any one please suggest me or tell me my mistake?
推荐答案
你这样做了艰辛的道路。摆脱的ByteBuffer
共有,并使用 DataOutputStream类
的所有方法。他们都是大端。我看不到任何的错误,但显然你必须发送一些同行不理解,所以他被关闭连接,而不是发送一个答复。
You're doing this the hard way. Get rid of the ByteBuffer
altogether and use all the methods of DataOutputStream
. They are all big-endian. I can't see any mistake but clearly you must be sending something the peer didn't understand so he is closing the connection instead of sending a reply.
注: Socket.isConnected()
不可能是假的,你要测试的地步。
Note: Socket.isConnected()
cannot possibly be false at the point you're testing it.
这篇关于读出并通过套接字写字节的数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!