[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1397
  • Last Modified:

Encode - decode UDP binary packets

I have a Java UDP server and client that currently communicate sending ASCII strings.  I need to be able to send binary packets instead from the client and have the server decode the packet and send back ACKNOWLEDGE  response packets also in binary format.  How can I accomplish this?  I found several examples for converting to and from text or binary files, but nothing specific for UDP packets.   I only have a basic Java programming knowledge, so please bear with me. Thanks in advance.
0
chelince
Asked:
chelince
  • 5
  • 2
1 Solution
 
CEHJCommented:
All you need to do is to put the Strings in, or take them out, as byte[]. For the default encoding:

// In
String s = "Hello World!";
byte[] bytes = s.getBytes();
// now copy into buffer

// Out

byte[] bytes = ............ (got out of packet buffer)
String s = new String(bytes);
0
 
chelinceAuthor Commented:
This turned out to be more complicated than it seemed at first.  The incoming UDP packet is 8 bytes long, my task is to receive it and send back an ACK by setting the MSB.  There may or may not be text data in the packet, the reason I was not seeing any data is that the first incoming packet has none, the remote sender is waiting for an ACK.  Your answer works for plain test, but now I have to get into setting bits.  If you can't help me I'll still give you the points and start a new question.  
0
 
CEHJCommented:
You can set the MSB thus

byte whateverByteOfThePacket |= (1 << 7);
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
(assuming you mean Most Significant Bit by 'MSB')
0
 
CEHJCommented:
and actually you're not likely to see it thus in your code. It's more likely to be

whateverByteOfThePacket |= (1 << 7);
0
 
chelinceAuthor Commented:
Thanks CEHJ, both suggestions worked and got me going.  
0
 
CEHJCommented:
8-)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now