sockets - How To create the packet and send using java? -
hi getting data gps device, want send response gps device creating packet packet this.
no. field type length description 1 smark char 6 flag of message (\r\n*kw\0) 2 packetle short 2 message length 3 cmd short 2 0x8200 4 cerrorcodechar 1 0x00ok, 0x01invalid deviceid 5 send char 2 message end "\r\n"
i want crete packet using code.
inetaddress ipaddress = receivepacket.getaddress(); string sendstring = "polo"; senddata = sendstring.getbytes(); datagrampacket sendpacket = new datagrampacket(senddata, senddata.length, ipaddress, port); serversocket.send(sendpacket);
i trying this.
bytearrayoutputstream bytearrypacket = new bytearrayoutputstream(); dataoutputstream dateoutputpacket = new dataoutputstream(bytearrypacket); dateoutputpacket.writechars("\r\n*kw\0"); dateoutputpacket.writeshort(15); dateoutputpacket.writeshort(82); dateoutputpacket.writechar('1'); dateoutputpacket.writechars("\r\n"); dateoutputpacket.flush(); byte[] result = bytearrypacket.tobytearray();
updated:
bytearrayoutputstream bytearrypacket = new bytearrayoutputstream(); dataoutputstream dateoutputpacket = new dataoutputstream(bytearrypacket); dateoutputpacket.writebytes("\r\n*kw\0"); dateoutputpacket.writeshort(15); dateoutputpacket.writeshort(82); dateoutputpacket.writebyte(1); dateoutputpacket.writebytes("\r\n"); dateoutputpacket.flush(); byte[] result = bytearrypacket.tobytearray();
updated 2:
try { bytearrayoutputstream bytearrypacket = new bytearrayoutputstream(); dataoutputstream dateoutputpacket = new dataoutputstream(bytearrypacket); dateoutputpacket.writebytes("\r\n*kw\0"); dateoutputpacket.writeshort(15); dateoutputpacket.writeshort(82); dateoutputpacket.writebyte(1); dateoutputpacket.writebytes("\r\n"); dateoutputpacket.flush(); byte[] result = bytearrypacket.tobytearray(); datagrampacket responsepacket = new datagrampacket(result, result.length, packet.getaddress(), packet.getport()); dsocket.send(responsepacket); } catch (ioexception ex) { ex.printstacktrace(); } catch (securityexception se) { se.printstacktrace(); } catch (illegalblockingmodeexception il) { il.printstacktrace(); } catch (illegalargumentexception ilg) { ilg.printstacktrace(); }
create dataoutputstream around bytearrayoutputstream; use various methods write data; bytes bytearrayoutputstream , wrap datagrampacket around that.
Comments
Post a Comment