• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1467
  • 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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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