-1

I'm getting an error on a snippet of my Java UDP server program when receiving a integer (the transaction ID) converted into a string from a separate client program:

CLIENT:

// Sending transaction ID to server
sendData = String.valueOf(transID).getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, sportno);
clientSocket.send(sendPacket);

SERVER:

// Receive client's transaction ID
receiveData = new byte[1024]; // 1024 byte limit when receiving
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket); // Server receives packet "100" from client
String clientMsg = new String(receivePacket.getData()); // String to hold received packet
int transID = Integer.valueOf(clientMsg); // Convert clientMsg to integer
System.out.println("Client has sent: " + transID); // Printing integer before iteration

While the client sends the packet just fine, during the string-to-integer conversion I get this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at server.main(server.java:46)

I've also used Integer.parseInt(clientMsg) with similar results. However, the program was able to print the packet as a string value just fine so long as I didn't try converting it into an integer.

Additionally, while it showed this in the terminal, when I copy+pasted this error message into this post the "100" was followed with a large amount of ""s from what I'm assuming are the rest of the empty bytes from the receiveData variable.

Would these empty values be the reason why my program failed? If not, what other reason would the program fail? Additionally, is there a way to send the transaction ID integer to the server without converting it to an string first to prevent this error?

Cody Kyrk
  • 3
  • 3

2 Answers2

0

Try hope this works

String receivedMsg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
Paul Jung
  • 26
  • 3
0
String clientMsg = new String(receivePacket.getData()); // String to hold received packet

The problem is here. You are appending junk, by ignoring the actual length of the incoming datagram. It should be:

String clientMsg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String to hold received packet
user207421
  • 305,947
  • 44
  • 307
  • 483
  • That did the trick, I appreciate the help. I have a question though about how the additional methods work: do said methods delete extra junk by first getting the length of the non-empty values with .getLength(), then .getOffset() getting rid of all of the "empty" junk outside of this length? – Cody Kyrk Nov 21 '17 at 22:48